Last active
January 13, 2023 00:21
-
-
Save drenther/665c0f1c6e96e7974e2961dc2f1bdb6f to your computer and use it in GitHub Desktop.
Example of using session with various mongoose methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love it. thanks for sharing