mongoose 对model的操作

链接数据库

let mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
let db = mongoose.connection;
db.on('error', () => {
  console.error('链接失败');
});
db.once('open', function () {
  //下面讲到的所有代码都在这里运行
});

Model#save([options], [options.safe], [options.validateBeforeSave], [fn])

保存model

Parameters参数:
[options] options optional options
[options.safe] overrides schema’s safe option
[options.validateBeforeSave] set to false to save without validating.
[fn] optional callback

Returns:

<Promise> Promise

See:
middleware

example:save([fn])

product.sold = Date.now();
product.save(function (err, product, numAffected) {
  if (err) ..
})
let Schema = mongoose.Schema;
let schema = new Schema({
    name: String,
    age: Number,
    occupation: String
});
let Person = mongoose.model('Person', schema);
let person = new Person({
    name:'马克',
    age:24,
    occupation:'programmer'
});
person.save(function(err,product,numberAffected){
    if(err){
        return console.error(err);
    }
    console.log(numberAffected); //1
});

回调将接收三个参数,err如果发生错误,product是保存的product,numberAffected,当文档在数据库中找到和更新时,为1,否则为0。

As an extra measure of flow control, save will return a Promise.

product.save().then(function(product) {
   ...
});

Model#remove([fn])

Removes this document from the db.

Parameters:

[fn]

<Promise> Promise

Example:

product.remove(function (err, product) {
  if (err) return handleError(err);
  Product.findById(product._id, function (err, product) {
    console.log(product) // null
  })
})
Person.findOne({name:'noshower'},function(err,result){
    if(err){
        return console.error(result);
    }
    console.log(result);//{ _id: 587a02251d73bb1ec61ace04, name: 'noshower',age: 22,occupation: 'teacher',__v: 1 }
    result.remove(function(err,result){
        if(err){
            return console.error(err);
        }
        Person.findById(result._id,function(err,result){
            if(err){
                return console.error(err);
            }
            console.log(result); //null 被删了
        })
    });
});

findByIdAndUpdate

Model.findByIdAndUpdate(id, [update], [options], [callback])

找到匹配的文档,根据update变量更新它,传递任何选项,并将找到的文档(如果有)返回到回调。如果回调被传递,则查询立即执行,否则返回一个Query对象。

Options:
new : true 返回修改的文档而不是原始文档。默认为true

//将new设置为false,将返回原始文档
    Person.findByIdAndUpdate('587a3aae75b3c5758ca6877d',{name:'光环'},{new:false},function(err,person){
    if(err){
        return console.error(err);
    }
    console.log(person);
    });

upsert:false 如果对象不存在,则创建对象。默认为false

//查找的id并不存在,将upsert设置为true,此时将创建对象
Person.findByIdAndUpdate('587a3aae75b3c5758ca687dd',{name:'光环'},{upsert:true},function(err,person){
 if(err){
     return console.error(err);
 }
 });

sort 如果按照条件找到多个文档,请设置排序顺序以选择要更新的文档
select 设置要返回的文档字段

Model.findOne

查找一个文档

Model.findOne(conditions, [fields], [options], [callback])

参考地址 mongoose API
简书参照地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值