【问题标题】:Mongoose: can't update in save callbackMongoose:无法在保存回调中更新
【发布时间】:2013-10-21 21:48:15
【问题描述】:

我有这个猫鼬模式:

var UrlSchema = new mongoose.Schema({
   description: String
});

然后,我创建一个模型距离:

var newUrl = new Url({
  "description": "test"
});

newUrl.save(function (err, doc) {

  if (err) console.log(err);
  else{
      Url.update({_id: doc._id},{description: "a"});
    }
});

但是执行了任何更新...为什么? 谢谢

【问题讨论】:

  • 我试过后效果很好。
  • @jibsales,您的编辑修复了代码,使问题变得毫无意义。 =)
  • 谢谢...我会把那个编辑放在我的答案中;)

标签: node.js mongodb mongoose


【解决方案1】:

更新方法需要添加回调或者调用#exec()进行更新:

var newUrl = new Url({
  "description": "test"
});

newUrl.save(function (err, doc) {

  if (err) console.log(err);
  else{

    Url.update({_id: doc._id},{description: "a"}, function (err, numAffected) {
        // numAffected should be 1
    });

    // --OR--
    Url.update({_id: doc._id},{description: "a"}).exec();

  }
});

仅供参考:我个人远离update,因为它绕过了默认值、设置器、中间件、验证等,这是使用像猫鼬这样的 ODM 的主要原因。我只在处理私有数据(无用户输入)和自动递增值时使用update。我会改写成这样:

var newUrl = new URL({
  "description": "test"
});

newUrl.save(function(err, doc, numAffected) {
  if (err) console.log(err);
  else {
    doc.set('description', 'a');
    doc.save();
  }
});

【讨论】:

  • 实际上,根据the docssave 回调需要三个参数:err、doc、numberAffected。
  • 哇,我从 1.x 开始就一直在使用 mongoose,但我从来没有遇到过这种情况……我猜是 RTFM。正在更新帖子...
猜你喜欢
  • 2015-12-25
  • 2016-01-11
  • 2017-12-07
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
  • 2015-07-18
相关资源
最近更新 更多