【问题标题】:Mongoose change document _id on save/updateMongoose 在保存/更新时更改文档_id
【发布时间】:2015-02-09 06:17:25
【问题描述】:

一个快速的:

当我推送更新时,为什么 Mongoose 会更改/升级文档的 _id 字段? 这是预期的行为吗?

谢谢。

这是我在 PUT 路由中使用的更新,它成功返回了更新后的模型,但不幸的是为 doc 提供了一个新的 _id

Document.findById(req.params.doc_id, function (err, doc) {
    if (err)
        res.send(err)

    // Do some subdoc stuff here …

    doc.save(function (err) {
        if (!err) {
            console.log('Success!');
            res.json(doc);
        } else {
            console.log(err);
        }

    });
});

【问题讨论】:

  • 你确定它实际上是一个更新吗?它不应该改变_id。使用一些代码会更容易弄清楚。
  • 抱歉有人投了你的票,不是我。

标签: node.js mongodb mongoose


【解决方案1】:

好的,问题解决了: 我记录了错误的_id(doh!)

【讨论】:

    【解决方案2】:

    猫鼬文档http://mongoosejs.com/docs/2.7.x/docs/model-definition.html 建议使用update 或findOne

    例如:

    var query = { name: 'borne' };
    Document.update({"_id": req.params.doc_id}, { name: 'jason borne' }, {}, function(err, numAffected){
      if (!err) {
        console.log('Success!');
        res.json(numAffected);
      } else {
        console.log(err);
      }
    });
    

    或

    Model.findOne({ "_id": req.params.doc_id }, function (err, doc){
      doc.name = 'jason borne';
      doc.save();
      // here you could use your save instead, but try not to use the doc again
      // it is confusing
      // doc.save(function (err, documentSaved, numberAffected) {
      //   if (!err) {
      //     console.log('Success!');
      //     res.json(documentSaved);
      //   } else {
      //     console.log(err);
      //   }
      // });
    });
    

    后来我还发现了一些文档http://mongoosejs.com/docs/documents.html 中建议的 findById 更新,这似乎是最新的,请检查您使用的版本,并仔细检查您在此处的函数中使用doc 的两次。您还可以检查您的 mongoDB 并查看是否有多个记录被保存。

    db.documents.find( {} )
    

    【讨论】:

    • 嗨。好吧,2.7 已经过时了,我使用 3.8.* 的 Mongoose。至于保存和更新,这真的取决于:我主要在保存时使用 Mongoose 中间件(前/后)来散列密码临时。这篇文章很好地描述了这一点:stackoverflow.com/questions/22278761/…
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 2017-10-09
    • 1970-01-01
    • 2015-04-07
    • 2021-03-10
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多