V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
IvanLi127
V2EX  ›  MongoDB

MongoDB 事务 + Promise.all(),会有部分数据操作失败。这是为啥?

  •  
  •   IvanLi127 · 2021-12-02 16:59:09 +08:00 · 1470 次点击
    这是一个创建于 847 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下面两段代码,第一段只有部分记录能更新成功,第二段代码正常。有大佬知道啥原因吗?

      await Promise.all(
          tuples.map(async ([list, count]) => {
            // await this.listModel.findOne({ _id: list }); // 存在这行也正常,不存在的话就不正常。
            await this.listModel.updateOne(
              { _id: list },
              {
                $inc: {
                  sampleCount: -count,
                },
              },
              { session },
            );
          }),
        );
    
      for (const [list, count] of tuples) {
          await this.listModel.updateOne(
            { _id: list },
            {
              $inc: {
                sampleCount: -count,
              },
            },
            { session },
          );
        }
    

    我排查了下,updateOne 方法都能返回修改成功一行数据,所以更新是成功的,但是最后事务执行完毕后只查到部分数据有正常更新。

    MongoDB 4.4 。

    IvanLi127
        1
    IvanLi127  
    OP
       2021-12-02 17:13:19 +08:00
    破案了,我在更上层的函数调用中漏写了个 await 导致这个问题。前面能成功也是刚好在事务提交前执行完毕了。我还以为遇到灵异事件了
    clf
        2
    clf  
       2021-12-02 18:13:20 +08:00
    MongoDB 事务唯一比较蛋疼的就是 Save/Insert 不能自动建集合了( SpringBoot 的 MongoTemplate ),所以现在会手动在跑项目的时候扫描一遍代码检查是否已经建了集合,没有的话就自动初始化集合。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5239 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 577ms · UTC 07:23 · PVG 15:23 · LAX 00:23 · JFK 03:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.