How to use the startSession function from mongoose

Find comprehensive JavaScript mongoose.startSession code examples handpicked from public code repositorys.

mongoose.startSession is a method that starts a new session for MongoDB database operations, allowing for transactions and more fine-grained control over database interactions.

38
39
40
41
42
43
44
45
46
47
if (isEmpty(peerId)) {
    console.error('peer id can not be empty');
    return { success: false };
}
checkImports();
const session = await mongoose.startSession();
session.startTransaction();
let tower, room, member1, member2, interaction, user, me;
try {
    user = (await UserFactory.instance().find({ id: peerId }, session)).toObject();
fork icon1
star icon0
watch icon1

139
140
141
142
143
144
145
146
147
148
149
}


module.exports.patch = async function (req, res, next) {
  const rs = { success: [], error: [], ok: 0 }
  if (!Array.isArray(req.body.data)) return res.status(500).send('invalid')
  const session = await mongoose.startSession()
  const transaction = await session.withTransaction(async () => {
    for await (let id of req.body.data) {
      try {
        rs.ok = await AProducts.flag(id, session)
fork icon0
star icon0
watch icon2

+ 14 other calls in file

How does mongoose.startSession work?

mongoose.startSession is a method provided by the Mongoose library that creates a new session for MongoDB database operations. When a new session is created using this method, a new transaction is automatically started, which allows multiple database operations to be grouped together and committed or rolled back as a single unit. This is useful for ensuring data consistency in complex operations that involve multiple documents or collections. To use mongoose.startSession, you first call the method to create a new session. You can optionally pass in an object with options to customize the behavior of the session, such as specifying the type of transaction or whether to enable causal consistency. Once the session is created, you can use it to perform database operations, such as querying or updating documents. All operations performed using the session are part of the same transaction, which can be committed or rolled back using the session.commitTransaction() or session.abortTransaction() methods, respectively. In addition to transactions, sessions also provide more fine-grained control over database interactions, such as the ability to read your own writes, use snapshot isolation, or execute read-only transactions. Sessions can also be used to specify options for queries, such as enabling a read concern or write concern. When you are done using the session, you should call the session.endSession() method to release the resources associated with it.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const session = await mongoose.startSession();
session.startTransaction();
try {
  const product = await Product.findById(productId).session(session);
  product.quantity -= quantityPurchased;
  await product.save();

  const order = new Order({
    customer: customerId,
    product: productId,
    quantity: quantityPurchased,
  });
  await order.save({ session });

  await session.commitTransaction();
} catch (err) {
  await session.abortTransaction();
  console.error(err);
} finally {
  session.endSession();
}

In this example, we start by creating a new session using mongoose.startSession(). We then start a transaction using session.startTransaction(). Inside the try block, we first find the product by its ID, using the session parameter to associate it with the session. We then update the quantity of the product, and save it back to the database. Next, we create a new Order document with the customer ID, product ID, and quantity purchased, and save it to the database using the session parameter to associate it with the same session. Finally, we commit the transaction using session.commitTransaction() to complete both database operations, or abort it using session.abortTransaction() if there was an error. If there was an error and the transaction was aborted, the catch block is executed and the error is logged. Regardless of the outcome, we end the session using session.endSession() to release the resources associated with it.