首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Mongoose中更新嵌套文档中任意数量的字段?

如何在Mongoose中更新嵌套文档中任意数量的字段?
EN

Stack Overflow用户
提问于 2020-11-18 14:19:23
回答 1查看 19关注 0票数 0

我需要更新Mongoose中嵌套数组的不同字段。有时我会发送runId和runStatus,有时发送siteFetched,有时发送siteInfo。

我尝试使用以下代码,但$set操作符替换了旧的字段。

模型:

代码语言:javascript
复制
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 },
                }],
            },
        },
    ],

下面是要更新的代码

代码语言:javascript
复制
  const campaign = await Campaign.findOneAndUpdate(
        { _id: campaignId, "keywords.keyword": keyword },
        {
            $set: { "keywords.$.apifySerp": {...serp }},
        }
    );

serp的值变化如下

代码语言:javascript
复制
 const serp = {
   runId: '1kLgbnvpADsDJyP1x',
   runStatus: 'READY'
 }

代码语言:javascript
复制
 const serp = {
        siteFetched: true
     }
EN

回答 1

Stack Overflow用户

发布于 2020-11-18 17:57:45

这是解决我的问题的代码。

代码语言:javascript
复制
const serp = {
    siteFetched: true,
};

let update = Object.keys(serp).reduce((acc, cur) => {
    acc[`keywords.$.apifySerp.${cur}`] = serp[cur];
    return acc;
}, {});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64888043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档