首页 > 解决方案 > 在 mongoose 中使用事务会引发错误

问题描述

这篇 SO 帖子中得到启发,我尝试使用 Mongoose 5.2.13 实现 MongoDB 的新事务功能。这是我的尝试:

addPost: async (parent, args) => {
  // Add new post to dbPosts
  const session = await dbPost.startSession();
  session.startTransaction();
  try {
    const opts = { session };
    const q1 = await dbPost({
      _id: new mongoose.Types.ObjectId(),
      title: args.title,
      content: args.content,
      author: {
        id: args.author_id,
        first_name: args.author_first_name,
        last_name: args.author_last_name,
      }
    }).save(opts);
    const q2 = await dbUser.findOneAndUpdate(
      {_id: args.author_id},
      {$push: {posts:
        {
          id: 'a14def', // need access to the _id field from q1
          title: args.title,
          content: args.content,
        }
      }},
    opts);
    await session.commitTransaction();
    session.endSession();
  } catch(err) {
    await session.abortTransaction();
    session.endSession();
    console.log('ERRORS:\n-----------\n' + err);
    console.log('\n------------\n\n');
    throw err;
  }
}

但是,运行上面的代码会返回以下错误:

BSON 字段“insert.autocommit”是一个未知字段。

这是什么意思,我的代码的哪一部分导致了它?另外,如何访问第一个操作(在这种情况下)生成的_id.save()以用于第二个操作(.findOneAndUpdate()在这种情况下)?目前,我只是在那里硬连线一个虚拟值:

id: 'a14def'

标签: node.jsmongodbmongoose

解决方案


推荐阅读