replacemongodb文档而不添加属性

我想我在这里有一个奇怪的。

我在快递中使用mongoose更新集合中的文档。 模型看起来像这样:

var customers = new Schema({ companyName: String, addressLine1: String, addressLine2: String, city: String, province: String, postal: String, businessPhone: String, contacts: [{ firstName: String, lastName: String, title: String, phone: String, email: String }], custCode: Number, rep: String }); 

以上是一个新模型,因为旧模型看起来像这样:

 var customers = new Schema({ companyName: String, firstName: String, lastName: String, addressLine1: String, addressLine2: String, city: String, province: String, postal: String, businessPhone: String, email: String custCode: Number, rep: String }); 

不同的是,我爆发了一个“联系人”数组,以便将来可以添加更多的联系人。 集合中的现有文档具有旧式样,更新对象具有新式样。

当我运行下面的代码时,文档最终会追加联系人数组,但也保留firstName和LastName,电子邮件等,而不是按照新模型的规则丢失它。

 var conditions = {custCode:req.body.customer.custCode} , update = req.body.customer , options = {upsert: false, new: true}; mongoose.model('customers').findOneAndUpdate(conditions, update, options, callback); function callback (err, doc) { if(err) { console.log("Errors: " + err); res.sendStatus(500); } else { console.log("Customer Saved! Rows affected: ", doc); res.sendStatus(200); }; }; 

我应该使用不同的mongoosefunction吗? 我应该使用$ unset吗?

我宁愿不做两个调用数据库(一个删除匹配的集合,另一个保存一个新的模型。

非常感谢!

您可以使用$unset删除contacts数组,并使用$set来添加新模型。

mongoose.model('customers').findOneAndUpdate(conditions, { $set:update, $unset: {'contacts': ''}}, options, callback);

findOneAndUpdate使用新数据修改现有文档。

您提供的选项不会修改文档replace。

  • upsert在当前不存在时影响新文档的创build。
  • new影响哪些数据是由函数返回的。 更新前或更新后。

如果在updatevariables中有完整的数据集,则可以用replaceOne完全replace现有的文档

 mongoose.model('customers').replaceOne(conditions, update, options, callback); function callback (err, doc) { if(err) { console.log("Errors: " + err); res.sendStatus(500); } else { console.log("Customer Saved! Rows affected: ", doc); res.sendStatus(200); }; };