假设我有一个如下所示的文档:
{ "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,email: [ new mongoose.Schema({ emailAddress: String,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} );
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。