collection.save给出重复

时间:2017-07-29 14:57:58

标签: node.js mongodb mongoose

手册说明了.save

  

如果存在,则替换它。当没有这样的文件时,它   将文档作为新文档插入

那么怎么可能得到这个错误?

Error: saveInvoice: WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error collection:
thaihome.invoice index: id dup key: { : 18 }",
"op":{"dueDate":1498885200,"_id":18,"property":"GVV-535","booking":"8KNKU","createDate":1498885200})

这是我的代码:

var invoiceModel = require('../../models/invoiceModel');
invoiceRecord = new invoiceModel(received.invoice)
invoiceRecord.save(function (err, res) {  
    if (err) {
        reject(new Error('saveInvoice: ' + err));
        return;
    }
    show("=====RESOLVE saveInvoice=====")
    resolve();
})

我可以看到mongoose尝试insert新记录,但记录已经存在。如果.save已经存在,我该如何更新?

1 个答案:

答案 0 :(得分:2)

您应该使用Model.update(conditions, doc, [options], [callback])

See the docs here

在选项对象中设置upsert:true

  

upsert(boolean)是否创建doc,如果它不匹配(false)