2014-12-10 117 views
0

快速之一:Mongoose更改文件_id保存/更新

爲什麼Mongoose在更新時更改/升級文檔的_id字段? 這是一個預期的行爲?

謝謝。

這是我在我的PUT路線內使用更新,並返回成功更新後的模型,但不幸的是一個新的_id爲DOC

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); 
     } 

    }); 
}); 
+3

您確定這是更新嗎?它不應該改變_id。這將更容易找出一些代碼。 – 2014-12-10 21:47:52

+1

對不起有人投票給你,是不是我。 – earlonrails 2014-12-10 22:34:11

回答

1

好了,問題就解決了: 我登錄了錯誤的_id (DOH!)

1

貓鼬文檔http://mongoosejs.com/docs/2.7.x/docs/model-definition.html 建議使用updatefindOne

例如:

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); 
    // } 
    // }); 
}); 

後來我也發現了findById更新的一些文檔http://mongoosejs.com/docs/documents.html建議,這似乎是最新的,請檢查您正在使用的版本,並仔細檢查了兩次,你是在你的函數中使用doc。你也可以檢查你的mongoDB,看看是否有多個記錄被保存。

db.documents.find({}) 
+0

嗨。那麼,2.7是過時的,我使用3.8 *的貓鼬。 至於保存和更新,它確實取決於:我主要使用Mongoose中間件(前/後)保存哈希密碼過渡。 這篇文章很好地描述了:http://stackoverflow.com/questions/22278761/mongoose-difference-between-save-and-using-update – wittgenstein 2014-12-11 08:42:03