整理一个入门级的CURD操作:
let mongoose=require('mongoose');
let Customer=mongoose.model("Customer",{cname:String,salary:Number,birth:Date});
mongoose.connect("mongodb://localhost:27017/demo01")
.then(con=>{
/*复位并添加一系列的试验数据*/
// resetDb(function () {
// addMany(function () {
// con.disconnect();
// })
// });
/*添加一个*/
// addCustomer(newObj=>con.disconnect())
/*删除一个*/
// deleteCustomer(rs=>{con.disconnect();console.log(rs)})
/*更新数据*/
update(newObj=>{con.disconnect();console.log(newObj)})
});
/* 数据清空 */
function resetDb(callback) {
Customer.deleteMany({}).then(()=>callback())
}
/* 添加一行数据 */
function addCustomer(callback) {
let c1=new Customer({cname:'tom',salary: 300.00,birth: new Date()});
c1.save().then(newObj=>callback(newObj));
}
/* 添加试验数据 */
function addMany(callback) {
let cs=[
{cname:'tom',salary: 300.00,birth: new Date(1988,9,21)},
{cname:'jackson',salary: 700.00,birth: new Date(1970,3,15)},
{cname:'alice',salary: 400.00,birth: new Date(1999,7,10)},
{cname:'john',salary: 900.00,birth: new Date(1977,1,5)},
{cname:'linus',salary: 1200.00,birth: new Date(1965,6,21)}
]
Customer.insertMany(cs,{ordered:true})
.then(newObjs=>callback(newObjs))
}
function deleteCustomer(callback) {
//成功的返回:{ n: 1, ok: 1, deletedCount: 1 }
Customer.deleteOne({_id:'5c8f528f80964d4d5382fcb3'})
.then(rs=>callback(rs))
}
function update(callback) {
Customer.findOneAndUpdate({_id:'5c8f4c2c29c37c4ced64929f'},{$inc:{salary:100}},{new:true})
.then(newObj=>callback(newObj))
}