假设我有一个如下所示的文档: { "personId": 13998272, "address": [ { "addressType": "HOME", "streetNo": 21, "addressLine1": "LORRAINE AVENUE", "addressLine2": "EDGEWATER", "city": "KINGSTON", "parish": "ST ANDREW", "country": "
{ "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} );