0

Taking cue from this SO post, I tried to implement MongoDB's new transactions feature using Mongoose 5.2.13. Here's my attempt:

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;
  }
}

Running the above code, however, is returning the following error:

BSON field 'insert.autocommit' is an unknown field.

What does it mean and what part of my code is causing it? Also, how do I access the _id generated by the first operation (.save() in this case) for use in the second operation (.findOneAndUpdate() in this case)? Currently, I am just hardwiring a dummy value there:

id: 'a14def'
TheLearner
  • 2,813
  • 5
  • 46
  • 94
  • Are you using a fresh MongoDB 4.0 installation or an updated one that used to be an older version? – dnickless Sep 18 '18 at 06:51
  • I haven't installed Mongo locally. My collections are in a MongoDB Atlas account. – TheLearner Sep 18 '18 at 06:53
  • Are you sure it's running v4.0? – dnickless Sep 18 '18 at 07:03
  • Also, do you have a replica set configured somehow? I am not using Atlas so this might be a given. But you need a replica set in order to run transactions: https://docs.mongodb.com/manual/replication/#transactions – dnickless Sep 18 '18 at 07:05
  • I do have replica sets with 3 nodes configured as a default Atlas feature. However, it seems my cluster is running version 3.6.7. And there isn't any way for me as the user to change that (the version option is disabled). – TheLearner Sep 18 '18 at 07:24
  • 1
    Well, that would explain the error. ;) Try this: https://resources.mongodb.com/mongodb-atlas-tutorial-kit/tutorial-upgrading-your-major-version-with-mongodb-atlas – dnickless Sep 18 '18 at 07:25
  • Okay, turns out M0 users are only allowed 3.6.7 on Atlas, so that's a bummer. Thanks for pointing out the issue. So do you think that should be the only bottleneck here, I mean no code gremlins in the snippet I've posted? – TheLearner Sep 18 '18 at 07:49
  • 1
    Nothing that strikes me as a guaranteed fail but I'm not a mongoose pro. – dnickless Sep 18 '18 at 07:56

0 Answers0