Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active January 13, 2023 00:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/665c0f1c6e96e7974e2961dc2f1bdb6f to your computer and use it in GitHub Desktop.
Save drenther/665c0f1c6e96e7974e2961dc2f1bdb6f to your computer and use it in GitHub Desktop.
Example of using session with various mongoose methods
const { runInTransaction } = require('mongoose-transact-utils');
const { User } = require('./models');
async function example() {
await runInTransaction(async session => {
// all the query methods listed here - https://mongoosejs.com/docs/queries.html
// session works with query methods as follows -
const user = await User.findOne({ }).session(session);
// as mentioned earlier, if you use save
// it will use the associated session ($session)
await users.save();
// apart from using $session to set another session
// you can also pass it as an option
await users.save({ session });
// you can also use the options object for passing session
await User.find({ }, null, { session });
// works with where as well
await User.where({ }).session(session);
// anywhere where queryOptions object can be passed, it accepts the session
// for example
await User.create([ /* some date */ ], { session });
await User.bulkWrite([ /* some update commands */], { session });
// session can be used with aggregation as well
await User.aggregate([
/* pipeline */
]).session(session);
// here is an example with populate, skip, limit, etc.
// you can chain session like all other similiar methods
await User.find({ }).skip(10).limit(10).populate('address').session(session);
});
}
@codeyourwayup
Copy link

Love it. thanks for sharing

@ashwins01
Copy link

Thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment