简体   繁体   English

如何同时更新 MongoDB 记录中的同一字段?

[英]How can i simultenously update the same field in a MongoDB Record?

I'm trying to update a particular field in a user row, and I'm using a forEach loop to do this, but it's only the last loop to run that gets updated.我正在尝试更新用户行中的特定字段,并且我正在使用 forEach 循环来执行此操作,但它只是运行的最后一个循环才会更新。 here's how my code looks:这是我的代码的外观:

const UserSchema = require('../models/UserSchema');

const updates = [100, 200];
const userID = req.user.id;

updates.forEach(update => {
    UserSchema.findByID(userID).then(user => {
        user.balance += update;
        user.save.then(user => console.log('user balance updated'));
    })
})

After running this code, the user's balance should be '300', but instead it's '200'..it's like the last one to run overwrites the first one because they're running at very close intervals, i can;t just wrap my head around this...please what's the solution?运行此代码后,用户的余额应该是“300”,但它是“200”......就像最后一个运行覆盖第一个,因为它们以非常接近的间隔运行,我不能只包装我的解决这个问题...请问有什么解决方案?

You are dealing with an async loop here, but the code doesn't wait for the promises to complete before moving onto the next.您在这里处理的是异步循环,但代码不会等待承诺完成,然后再进入下一个。

It's much easier using an async function.使用async function 会容易得多。

async function updateBalances(userID, updates){
    for (const update of updates) {
      const user = await UserSchema.findByID(userID)
      user.balance += update
      await user.save()
    }
    console.log('user balances updated')
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更新 mongodb 中集合的特定记录的字段? - How do i update a field for a specific record of a collection in mongodb? 如何部分更新 MongoDB 中的字段,以便新字段将一些文本添加到现有记录 - How do I partially update a field in MongoDB so the new field will add some text to exisiting record 如何使用过滤器 _id 找到一条记录并使用 nodejs 和 mongodb,mongoose 更新该记录 - how can i find one record with the filter _id and update that record using the nodejs and mongodb,mongoose 如何通过使用 nodejs 在 mongodb 中指定其匹配字段之一来修改记录的字段 - How can i modify a field of a record by specifying one of its matching field in mongodb using nodejs 如何通过跳过 nodejs 中 Mongoose 模式中标记为必需的字段来将记录保存到 mongoDB? - How can I save a record to mongoDB by skipping a field which is marked as required in the Mongoose schema in nodejs? 在MongoDB中创建新记录时,如何将多个项目保存到数组字段中? - How can I save multiple items to an array field when creating a new record in MongoDB? 如何在不更新每个字段的情况下更新mongodb字段? - How can i update a mongodb field without having a single route for every individual field to be updated? 为什么我可以在MongoDB中更新一个字段,而不更新另一个字段? (MEAN Stack) - Why can I update one field but not another in MongoDB? (MEAN Stack) 我如何在mongoDB中同时在两个不同的数据库中插入和更新文档 - How can i insert and update document in two different databases at the same time in mongoDB 如何自动更新mongodb字段 - how to auto update mongodb field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM