admin管理员组文章数量:1355529
I inserted a client in my "clients" collection.
data inserted
{
"type": "private",
"name": "Client 1",
"contact": {
"email": "[email protected]",
"phone": {
"dialCode": "242",
"number": "066788998"
},
"location": {
"address": "69 Fake Avenue",
"city": "Fake City",
"country": "Fake country",
"state": null
}
}
}
Now I want to update client's email.
With my API, i submit this data to update client's email.
{
"contact": {
"email":null
}
}
mongodb/mongoose is updating contact but phone and location are removed. Why ?
This is how i update my data await Client.findByIdAndUpdate(id, {$set: data}})
.
How to only update email
without removing other data ? How to update a nested object
I inserted a client in my "clients" collection.
data inserted
{
"type": "private",
"name": "Client 1",
"contact": {
"email": "[email protected]",
"phone": {
"dialCode": "242",
"number": "066788998"
},
"location": {
"address": "69 Fake Avenue",
"city": "Fake City",
"country": "Fake country",
"state": null
}
}
}
Now I want to update client's email.
With my API, i submit this data to update client's email.
{
"contact": {
"email":null
}
}
mongodb/mongoose is updating contact but phone and location are removed. Why ?
This is how i update my data await Client.findByIdAndUpdate(id, {$set: data}})
.
How to only update email
without removing other data ? How to update a nested object
2 Answers
Reset to default 1I don't think there is a generic solution to handle all sorts of payload. But for your current use case of updating contact.email
, you can use $mergeObjects
in an update with aggregation pipeline.
db.collection.update({
"_id": 1
},
[
{
"$set": {
"contact": {
"$let": {
"vars": {
"payload": {
"contact": {
"email": null
}
}
},
"in": {
"$mergeObjects": [
"$contact",
"$$payload.contact"
]
}
}
}
}
}
])
Mongo Playground
Instead of replacing the entire contact object, update only the email field using MongoDB's dot notation as contact.email
await Client.findByIdAndUpdate(
id,
{ $set: { "contact.email": <New_Email> } },
{ new: true, runValidators: true }
);
returns updated doc & enforce schema validation
本文标签: nodejsMongoose update nested data without erase other dataStack Overflow
版权声明:本文标题:node.js - Mongoose update nested data without erase other data - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744011871a2575717.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
contacts
part of your document with the api data which has only the email it replaces the contents .ideally$set: { "contact.email": null }
should only update the email. but if you need to be more dynamic you might have to transform your api data before feeding into the query – cmgchess Commented Mar 29 at 16:38