mjperhuo 2019-06-30
Mongoose是一个对象文档模型(ODM)库,它对Node原生的MongoDB模块进行了进一步的优化封装,并提供了更多的功能。mongoose的优势在于:
Mongoos的几个对象概念:
npm i mongoose --save
关于npm install、npm install --save的区别来自于https://blog.csdn.net/qq_3037...
let mongoose = require("mongoose");
mongoose.connect('mongodb://user:pwd@ip:27017/database');
let db = mongoose.connection; db.on('error',()=>{ console.log('连接失败'); }); db.once('open',()=>{ console.log('连接成功'); }); db.once('close',()=>{ console.log('断开连接'); });
let Schema = mongoose.Schema; let personSchema = new Schema({ name:String, age:Number, sex:{ type:String, default:"F" } });
关于schema的学习来自于:
let personModel = mongoose.model("persion",personSchema);
因为我在启动mongodb时加了 --auth参数,插入操作是需要验证用户权限。
db.createUser({ user: "test01", pwd: "test01", roles: [{ role: "readWrite", db: "test" }] })
//插入操作 /*personModel.create({ name:"t01", age:22 },(err)=>{ if(!err){ console.log("插入成功"); }else{ throw err; } });*/ //修改操作 //update报错: DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.,改成updateOne /*personModel.updateOne({_id:"5c2d7c0bda87713ff850c6ea"},{$set:{name:"t02"}},(err)=>{ if(err){ throw err; } });*/ /*personModel.updateOne({_id:"5c2d7af402a3462c7c212b58"},{$set:{name:"t01"}},(err)=>{ if(err){ throw err; } });*/ //查找 /*personModel.find({},(err,docs)=>{ if(!err){ console.log(docs); }else{ throw err; } });*/ /*personModel.find({name:"t01"},(err,docs)=>{ if(!err){ console.log(docs); }else{ throw err; } });*/ /*personModel.find({},"name age _id",{skip:1,limit:2},(err,docs)=>{ if(!err){ console.log(docs); }else{ throw err; } });*/ //删除 /*personModel.remove({name:"t03"},(err)=>{ if(!err){ console.log("删除成功"); } });*/