首页 文章

将数组值添加到MongoDB中,其中元素不在数组中

提问于
浏览
2

在MongoDB中,这是我的 account 文档的简化结构:

{
    "_id" : ObjectId("5a70a60ca7fbc476caea5e59"),
    "templates" : [ 
        {
            "name" : "Password Reset",
            "content" : "AAAAAAAA"
        },
        {
            "name" : "Welcome Message",
            "content" : "BBBBBB"
        }
     ]
}

有一个类似的 default_templates 集合

let accnt = await Account.findOne({ _id: req.account._id }, { templates: 1 });
let defaults = await DefaultTemplate.find({}).lean();

我的目标是在帐户下找到丢失的模板,并从默认值中获取它们 . (a)我需要upsert templates 如果它没有想要更新模板(如果它已经存在于帐户中) .

我尝试过以下方法:

if (!accnt.templates || accnt.templates.length < defaults.length) {

  const accountTemplates = _.filter(accnt.templates, 'name');
  const templateNames = _.map(accountTemplates, 'name');

  Account.update({ _id: req.account._id, 'templates.name' : { $nin: templateNames } },
      { '$push': { 'templates': { '$each' : defaults } } }, { 'upsert' : true },
      function(err, result) {
        Logger.error('error %o', err);
        Logger.debug('result %o', result);
      }
  );
}

这在upsert中成功,但即使 templateNames 中有匹配的名称,它也会输入所有默认模板 . 我已经验证 templateNames 数组是正确的,我也尝试使用 $addToSet 而不是 $push ,所以我不能理解Mongo子网查询 .

关于我做错了什么的任何想法?

编辑:我通过在更新之前简单地从默认数组中删除元素来实现这一点,但我仍然想知道如何使用Mongoose实现这一点 .

1 回答

  • 1

    您可以尝试使用mongodb中的bulkWrite操作

    Account.bulkWrite(
      req.body.accountTemplates.map((data) => 
        ({
          updateOne: {
            filter: { _id: req.account._id, 'templates.name' : { $ne: data.name } },
            update: { $push: { templates: { $each : data } } },
            upsert : true
          }
        })
      )
    })
    

相关问题