You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constuserSchema=newSchema({name: String,age: Number,email: String,createAt: Date,updateAt: Date,bestFriend: mongoose.Schema.Types.ObjectId,hobbies: [String],address: {street: String,city: String},// use another schemaaddress2: addressSchema});
MongoDB Operation Example
constmongoose=require('mongoose');constUser=require('./user');mongoose.connect('mongodb://localhost:27017/test')asyncfunctionrun(){// create new userconstuser=newUser({name: 'John',email: '[email protected]'});awaituser.save();// sync to database// create another user on databaseconstuser2=awaitUser.create({name: 'Bob',email: '[email protected]'});constusers=awaitUser.find();console.log(users);}run()
Schema Validataion
constuserSchema=newSchema({name: String,age: {type: Number,min: 1,max: 100,validate: {// customize validatorvalidator: v=>v%2,message: props=>`${props.value} is not an even number`}}email: {type: String,minLength: 10,required: true,// must provide email when creating new userlowercase: true,// automatically convert string to lowercase},createAt: {type: Date,immutable: true,// never let us change it default: ()=>Date.now(),// default value},bestFriend: {type: mongoose.Schema.Types.ObjectId,ref: "User"// tells mongoose what model does this object id reference},});
schema validation in mongoose only works on create() or save().
but there's a bunch of other methods built into mongoose that you can use to update things in your database without using the create() or save() method, and those don't go through validation because they work directly on the mongodb database.
don't use those method, such like findByIDAndUpdate, updateOne, updateMany, those do not go through validataion.
which I always recommend you always doing just a normal findByID or findOne() get your user and then save() it.
// instance methoduserSchema.methods.sayHello=function(){console.log('Hello, my name is '+this.name);}// static methoduserSchema.statics.findByName=function(name){returnthis.find({name: newRegExp(name,'i')});}// query methoduserSchema.query.byName=function(name){// this is going to be chainable with a queryreturnthis.where({name: newRegExp(name,'i')});}// virtual propertyuserSchema.virtual('fullName').get(function(){returnthis.name.first+' '+this.name.last;});// use: user.fullName// middle wareuserSchema.pre('save',function(next){this.updateAt=newDate();next();});userSchema.post('save',function(doc,next){doc.sayHello()next();});