说我有一个看起来像这样的文件:

{
  "personId": 13998272,
  "address": [
    {
      "addressType": "HOME",
      "streetNo": 21,
      "addressLine1": "LORRAINE AVENUE",
      "addressLine2": "EDGEWATER",
      "city": "KINGSTON",
      "parish": "ST ANDREW",
      "country": "JAMAICA",
      "qScore": 0.9,
      "modifiedDate": "2019-02-17 15:24:19"
    }
  ],
  "phone": [
    {
      "originalNumber": "+18767842983",
      "phoneNumberIFormat": "+18768514679",
      "phoneNumberLFormat": "8768514679",
      "qualityScore": 0.8,
      "dataSource": "PERSON",
      "modifiedDate": "2018-12-17 09:42:31"
    }
  ],
  "email": [
    {
      "emailAddress": "neilagreen78@yahoo.com",
      "dataSource": "FINACLE",
      "qualityScore": 0.89,
      "modifiedDate": "2018-12-17 09:38:41"
    }
  ]
}


我的架构在以下代码段中定义,以供引用:

const contactSchema = new mongoose.Schema({
  pid: Number,
  address: [
    new mongoose.Schema({
      addressType: String,
      streetNo: String,
      addressLine1: String,
      addressLine2: String,
      city: String,
      parish: String,
      country: String,
      qScore: String,
      modifiedDate: String
    })
  ],
  phone: [
    new mongoose.Schema({
      originalNumber: String,
      phoneNumberIFormat: String,
      phoneNumberLFormat: String,
      qualityScore: Number,
      dataSource: String,
      modifiedDate: String
    })
  ],
  email: [
    new mongoose.Schema({
      emailAddress: String,
      dataSource: String,
      qualityScore: Number,
      modifiedDate: String
    })
  ]
});


如何在不覆盖其他嵌入文档的情况下更新每个嵌入文档的数组?

如果说请求是使用和地址和电子邮件对象而不是电话,那么我将如何处理呢?

最佳答案

你可以试试这个..

获取联系人对象的结构,然后检查以查看req.body中发送了哪些属性,并相应地构建了查询。

N.B:您必须具有一些验证才能检查请求正文,以确保没有发送不需要的属性。您可以使用Joi之类的软件包


const getContact = await contact.findOne({ id: req.params.id });

let query = { $addToSet: {} };
  for (let key in req.body) {
    if (getContact[key] && getContact[key] !== req.body[key])// if the field we have in req.body exists, we're gonna update it
      query.$addToSet[key] = req.body[key];
  }

  const contact = await Customer.findOneAndUpdate(
    { pid: req.params.id },
    query,
    {new: true}
  );

09-17 16:42
查看更多