[英]Mongoose find and update json in json
I'm sorry if title isn't clear I didn't know how else to put this.如果标题不清楚,我很抱歉我不知道还能怎么写。
Let's say I have the following schema:假设我有以下架构:
{
name: {
type: String
},
additionalInfo: {
someInfo: {
a: {
type: String
},
b : {
type: String
}
}
}
}
Now say I want to make a function that changes field b
and ONLY b
.现在说我想创建一个更改字段b
和仅b
的函数。
function changeB(id, newB) {
return new Promise((resolve, reject) => {
myModel.findByIdAndUpdate(id, { additionalInfo: { someInfo: { b } } }, (err, doc) => {
if(err) reject(err);
if(doc) resolve(doc);
reject();
});
});
}
Problem here is that function overwrites entire additionalInfo
for that document.这里的问题是该函数会覆盖该文档的整个additionalInfo
信息。 So if I had a a
value in it as well, after running that function it'll be gone.所以如果我也有a
值,在运行该函数后它就会消失。 What should I do to only change additionalInfo.someInfo.b
?我该怎么做才能只更改additionalInfo.someInfo.b
?
Actually while writing this question (especially on that last sentence) I figured it out myself.实际上,在写这个问题时(尤其是最后一句话),我自己想通了。 Following function only changes additionalInfo.someInfo.b
without deleting anything else.以下函数仅更改additionalInfo.someInfo.b
而不删除任何其他内容。
function changeB(id, newB) {
return new Promise((resolve, reject) => {
myModel.findByIdAndUpdate(id, { 'additionalInfo.someInfo.b': newB }, (err, doc) => {
if(err) reject(err);
if(doc) resolve(doc);
reject();
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.