gpt4 book ai didi

arrays - 将数组值添加到元素不在数组中的 MongoDB

转载 作者:可可西里 更新时间:2023-11-01 09:38:31 24 4
gpt4 key购买 nike

在 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) 如果帐户中不存在 templates,我需要更新它;(b) 如果帐户中已经存在,我不想更新模板。

我试过以下方法:

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

这在更新插入时成功,但它会输入所有默认模板,即使在 templateNames 中有匹配的名称也是如此。我已经验证 templateNames 数组是正确的,我也尝试过使用 $addToSet 而不是 $push,所以我一定不了解 Mongo子文档查询。

对我做错了什么有什么想法吗?

编辑:我已经通过在更新之前简单地从默认数组中删除元素来实现它,但我仍然想知道如何使用 Mongoose 完成它。

最佳答案

你可以试试bulkWrite 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
}
})
)
})

关于arrays - 将数组值添加到元素不在数组中的 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com