将数组值添加到MongoDB中,其中元素不在数组中 [英] Add array values into MongoDB where element is not in array

查看:533
本文介绍了将数组值添加到MongoDB中,其中元素不在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In MongoDB, this is the simplified structure of my account document:

{
    "_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)如果帐户中不存在templates,我需要补高(b)如果帐户中已经存在模板,则我不想更新它.

My goal is to find the missing templates under account and grab them from defaults. (a) I need to upsert templates if it doesn't exist in an account and (b) I don't want to update a template if it already exists in an account.

我尝试了以下操作:

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子文档查询.

This succeeds at the upsert but it will enter all default templates even if there's a matching name in templateNames. I've verified that templateNames array is correct and I've also tried using $addToSet instead of $push, so I must not understand Mongo subdoc queries.

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

Any ideas on what I'm doing wrong?

我已经通过在更新之前简单地从默认数组中删除元素来使它起作用,但是我仍然想知道如何使用Mongoose来实现.

I've gotten this to work by simply removing elements from the defaults array before updating, but I'd still like to know how this could be accomplished with Mongoose.

推荐答案

您可以尝试 bulgorite 在mongodb中的操作

You can try with bulkWrite operation in mongodb

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
      }
    })
  )
})

这篇关于将数组值添加到MongoDB中,其中元素不在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆