【问题标题】:ClientSession cannot be serialized to BSON - Mongodb TransactionClientSession 无法序列化为 BSON - Mongodb Transaction
【发布时间】:2022-01-24 08:55:13
【问题描述】:

我对 mongodb 事务还很陌生,所以我不知道我做错了什么。我已按照文档中的说明进行操作,但仍然出现此错误

{
"status": 400,
"name": "Error",
"message": "ClientSession cannot be serialized to BSON."
}

这是我的代码

    async createInsurance(params) {
    const session = await db99.startSession();
    try {
      session.startTransaction();
      const doc = await db.insurance
        .find({ session })
        .sort({ createdAt: -1 })
        .limit(1)
        .lean();
      const latest = doc[0];
      const payload = { ...params, id: latest ? latest.id + 1 : 1 };
      const data = await db.insurance.create(payload, { session });

      await mongoTransaction.commitWithRetry(session);
      const result = defaultResult('SuccessCreateInsurance', SuccessCreateInsurance[this.lang], data, 200);
      return result;
    } catch (error) {
      logger.log('error', 'ProductService-createInsurance', { error });
      throw error;
    } finally {
      await session.endSession();
    }
  }

有什么我错过的吗?

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

Model.create 的文档表明必须以数组的形式传递文档才能指定选项:

[options] «Object» 选项传递给 save()。要指定选项,文档必须是数组,而不是展开。

改变

const payload = { ...params, id: latest ? latest.id + 1 : 1 };

const payload = [{ ...params, id: latest ? latest.id + 1 : 1 }];

【讨论】:

    【解决方案2】:

    原来我必须在 find 方法的第三个参数上传递 session 并将有效负载包装为 create 方法的数组,因为它只能采用数组。 代码将如下所示

    async createInsurance(params) {
        const session = await db99.startSession();
        session.startTransaction();
        try {
          const doc = await db.insurance
            .findOne(null, null, { session })
            .sort({ createdAt: -1 })
            .limit(1)
            .lean();
          const latest = doc[0];
          const payload = { ...params, id: latest ? latest.id + 1 : 1 };
          const data = await db.insurance.create([payload], { session });
    
          await session.commitTransaction();
          const result = defaultResult('SuccessCreateInsurance', SuccessCreateInsurance[this.lang], data, 200);
          return result;
        } catch (error) {
          await session.abortTransaction();
          logger.log('error', 'ProductService-createInsurance', { error });
          throw error;
        } finally {
          await session.endSession();
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 2011-10-23
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      相关资源
      最近更新 更多