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'