Mongo DB保存尝试插入而不是更新
我正在做一个Mongo Schema.save(),它应该自动做一个upsert,但它坚持尝试做一个插入,然后错误
E11000 duplicate key error index
这是保存的Nodefunction:
exports.ImpdateSave = function(req, res) { var theImpdate = new Impdate(req.body) if (theImpdate){ var impdateId = req.params.id; console.log("Node API Impdate: ", theImpdate); console.log("Node API Impdate ID: ", impdateId); theImpdate.save(function(err) { if (err) { console.log(err); return res.send(400); } res.send(200); }); } else { return res.status(400).send('There was no person data in the request to update. Please try again!'); } };
为什么在插入/更新之前执行初始search时无法find文档,但是在插入时发现它?
控制台输出:
Node API Impdate: { _id: 5481c33cd8bf24f4235cff35, _creator: 54679200502e901427fec6de, name: 'XXXXX', address: 'XXXXXXXXXXXXXXXX', __v: 0} Node API Impdate ID: 5481c33cd8bf24f4235cff35 { [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: fullstack-dev.impdates.$_id_ dup key: { : ObjectId('5481c33cd8bf24f4235cff35') }] name: 'MongoError', code: 11000, err: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: fullstack-dev.impdates.$_id_ dup key: { : ObjectId(\'5481c33cd8bf24f4235cff35\') }' }
mongoose的save
不会像你想的那样做一个高位。 当你像这样创build一个新的Impdate
对象时,即使所包含的_id
值已经存在,它也会将其视为一个新的文档。
相反,要么通过其_id
文档,应用正文中的新值并save
,或使用findByIdAndUpdate
。