我需要更新Mongoose中嵌套数组的不同字段。有时我会发送runId和runStatus,有时发送siteFetched,有时发送siteInfo。
我尝试使用以下代码,但$set操作符替换了旧的字段。
模型:
campaignId: { type: String },
keywords: [{
keyword: { type: String },
serp: {
runId: { type: String },
runStatus: { type: String },
siteFetched: { type: Boolean },
sitesInfo: [{
title: { type: String },
url: { type: String },
description: { type: String },
}],
},
},
],下面是要更新的代码
const campaign = await Campaign.findOneAndUpdate(
{ _id: campaignId, "keywords.keyword": keyword },
{
$set: { "keywords.$.apifySerp": {...serp }},
}
);serp的值变化如下
const serp = {
runId: '1kLgbnvpADsDJyP1x',
runStatus: 'READY'
}和
const serp = {
siteFetched: true
}发布于 2020-11-18 17:57:45
这是解决我的问题的代码。
const serp = {
siteFetched: true,
};
let update = Object.keys(serp).reduce((acc, cur) => {
acc[`keywords.$.apifySerp.${cur}`] = serp[cur];
return acc;
}, {});https://stackoverflow.com/questions/64888043
复制相似问题