gpt4 book ai didi

javascript - 有没有一种方法可以更新多个文档以将特定数字添加到一列而不使用循环

转载 作者:行者123 更新时间:2023-12-03 07:48:44 24 4
gpt4 key购买 nike

我正在将 SailsJS 与 MongoDB 结合使用,并且有一个如下所示的模型:

module.exports = {
attributes: {

name : { type: 'string' },
openDate: { type: 'date' },
}
}

数据库中有数百个文档。现在我有一个包含名称列表的数组。并且需要在名为列表的 openDate 上添加 30 天。有没有一种方法可以在不创建循环并在循环内获取名称并一一更新 openDate 的情况下执行此操作,但使用一个 collections.update 来实现这一点?目前我只有代码来查找名称在列表中的所有文档,但不知道下一步该怎么做。

Accounts.find({
name:{ $in : nameList}
}).exec(function(err, data) {


});

最佳答案

除非您可以对所有记录应用相同的日期(我相信这不是您想要的),否则答案是否定的。没有机制可以做到这一点,但应该是(你或某人应该在他们的 github 存储库上提出它),至少将 ids 数组传递给条件,并将匹配的值数组作为 update 的第二个参数传递,并且根据文档,您可以传递一个值数组,但我已经测试过它,它会抛出一个错误(至少在 mysql 适配器上),并且没有测试来支持该功能。

所有示例都使用 lodashes6 arrow 函数,并假设您有一个 increaseDates 的 fn)

因此,如果您可以使用相同的值,那么您可以这样做:

Accounts.find({name:{ $in : nameList}}).exec(function(err, data) {
// error handling here
var criteria = _.map(data, 'id'); // same as pluck
Accounst.update(criteria, {openDate: increaseDate(x.openDate)}).exec(...);
});

猜测上述不是一个选项,您需要使用异步串行或并行之类的东西,如下所示:

Accounts.find({name:{ $in : nameList}}).exec(function(err, records) {
// error handling here
tasks = _.map(records, (x)=> Accounts.update(x.id, {openDate: increaseDate(x.openDate)}, callback));
async.parallel(tasks, function(err, results){});
});

就我而言,我使用 async/await因此,执行此操作即可,更新将按顺序运行:

  async(()=> {
records = await (Accounts.find({name:{ $in : nameList}});
_.each(records, (x)=> await (Accounts.update(x.id, {openDate: increaseDate(x.openDate)}));
})()

或者并行运行它们,像这样

  async(()=> {
records = await (Accounts.find({name:{ $in : nameList}});
tasks = _.map(records, (x)=> Accounts.update(x.id, {openDate: increaseDate(x.openDate)}));
await (tasks)
})()

关于javascript - 有没有一种方法可以更新多个文档以将特定数字添加到一列而不使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093398/

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