本文最后更新于:19 小时前
mongoose的Model对应于「类」,documents对应于「实例」, mongoose对应于MongoDB的collection,documents对应于每一条记录
mongoose使用指南 一、快速创建连接 参考:Mongoose 5.0 中文文档 (mongoosejs.net)
二、Schema属性的options 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 var schema3 = new Schema ({ test : { type : String , lowercase : true , uppercase : true , required :true , default :'star' , index:true , unique:true , sparse:true , match:RegExp , enum:Array , min:Number , max:Number , trim :true capped :1024 validate:function ,为此属性添加一个验证器函数,如demo1所示 get:function , set:function , } });
参考:mongoose Schema写法 - yun迹 - 博客园 (cnblogs.com)
2.2、不重复的key,使用unique 1 2 3 4 5 6 7 8 var uniqueUsernameSchema = new Schema ({ username : { type : String , unique : true } });var U1 = db.model ('U1' , uniqueUsernameSchema);var U2 = db.model ('U2' , uniqueUsernameSchema);
三、Schema中自定义函数 可以定义实例方法,也可以定义静态方法。可以定义快捷查询助手
在定义Schema时,添加示例方法;然后用model创建documents实例(对应于MongoDB中的collection);之后就可以使用自定义的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 var animalSchema = new Schema ({ name : String , type : String }); animalSchema.methods .findSimilarTypes = function (cb ) { return this .model ('Animal' ).find ({ type : this .type }, cb); }; var Animal = mongoose.model ('Animal' , animalSchema); var dog = new Animal ({ type : 'dog' }); dog.findSimilarTypes (function (err, dogs ) { console .log (dogs); });
自定义方法不要使用箭头函数
1 2 3 4 5 6 7 8 9 animalSchema.query .byName = function (name ) { return this .find ({ name : new RegExp (name, 'i' ) }); }; var Animal = mongoose.model ('Animal' , animalSchema); Animal .find ().byName ('fido' ).exec (function (err, animals ) { console .log (animals); });
参考:Mongoose 5.0 中文文档 (mongoosejs.net)
四、collection命名 调用mongoose.model函数时,MongoDB会自动将collection的名称改为「全小写+复数」 形式
五、自动更新修改记录的时间 参考:
[1].Mongoose Schemas中定义日期以及timestamps选项的妙用 - 都市烟火 - 博客园 (cnblogs.com)
[2].Mongoose 5.0 中文文档 (mongoosejs.net)
六、mongoose查询 Mongoose 中每一处查询,被传入的回调函数都遵循 callback(error, result) 这种模式。查询结果的格式取决于做什么操作: findOne() 是单个文档(有可能是 null ),find() 是文档列表, count() 是文档数量,update() 是被修改的文档数量。
大多数find*的参数格式都是查询参数、结果字段、回调函数
1 2 3 Person .findOne ({ 'name.last' : 'Ghost' }, 'name occupation' , (err, person ) => { })
七、批量删除 [MongoDB中如何优雅地删除大量数据 - iVictor - 博客园 (cnblogs.com)](https://www.cnblogs.com/ivictor/p/15457454.html#:~:text= 在MongoDB中,如果要删除大量数据,推荐使用deleteMany %2B,ObjectID进行批量删除。 为了保证操作的安全性及规避批量操作带来的主从延迟风险,建议在执行删除操作时,将Write Concern设置为w%3A “majority”。)
参考链接