Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

node.js - Why I am getting error as startSession is not a function while using transactions in mongoose in nodejs?

I want to deal with the transactions in my entire code. For that I am using async/await code and has initialized the sessions as well. And using the latest mongoDB version as well. I dont why its throwing this error? I am getting the following console error:

(node:8704) UnhandledPromiseRejectionWarning: TypeError: mongoose.startSession is not a function

(node:8704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To termina
te the node process on unhandled promise rejection, use the CLI flag `--unhandle
d-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejectio
ns_mode). (rejection id: 1)
(node:8704) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
 Node.js process with a non-zero exit code.

What I am doing wrong?

    var mongoose = require('mongoose');

 router.route('/update-sources').get(async (req, res) => {
      const session = await mongoose.startSession();
    
      var arrComm = [];
      var mailOptions2, count = 0;
    
      console.log("Came under /update-sources and "+ req.query.selectedValue);
    
      if(req.query.selectedValue == 'In Progress')
      {
        try {
          session.startTransaction();
          var eleTopic, eleStatus;
          let data = await User.findOne({tag:"Client","Addtasks.commonID":req.query.commonIDs}, {session});
    
          if(data.alertInProgress == 'checked'){
            data.Addtasks.forEach(async (element) => {
              if(element.commonID == req.query.commonIDs)
              {
                eleTopic = element.topic;
                eleStatus = element.status
              }
            });
            if(eleStatus == "Requirement Submitted")
            {
              await sendMails2Client(data.email, eleTopic, 'Requirement Submitted', 'In Progress');
              console.log("data.status while sending mail to Client for Rev. Req.");
            }
            else if(eleStatus == 'Revision Required')
            {
              await sendMails2Client(data.email, eleTopic, 'Revision Required', 'In Progress');
              console.log("data.status while sending mail to Client for Rev. Req.");
            }
          }
          else {
            console.log("Nothing happened!!!");
          }
    
          let success = await User.updateMany({"Addtasks.commonID":req.query.commonIDs},
          {$set: {"Addtasks.$.width" :'250px',
          "Addtasks.$.height" :'32px',
          "Addtasks.$.background" :'linear-gradient(45deg, #091B6A, #0029FF)',
          "Addtasks.$.border_radius" :'10px / 5px',
          "Addtasks.$.status" :req.query.selectedValue}}, {session});
          if (success) {
            console.log("In Progress color set!");
            let dataWriter = await User.findOne({tag:"Writer","Addtasks.commonID":req.query.commonIDs}, {session})
            dataWriter.Addtasks.forEach(async (element) => {
              if(element.commonID == req.query.commonIDs)
              {
                await sendMails2User(dataWriter.email, element.topic, 'Requirement Submitted', 'In Progress');
                let dataAdmin = await User.findOne({tag:"Admin","Addtasks.commonID":req.query.commonIDs}, {session})
                await sendMails2User(dataAdmin.email, element.topic, 'Requirement Submitted', 'In Progress');
                return res.end('{"success" : "Updated Successfully", "status" : 200}');
              }
            })
          }
          await session.commitTransaction();
          session.endSession();
        } catch (error) {
          await session.abortTransaction()
          session.endSession()
          console.log(err)
          res.send('Error = '+ err);
        }
      }
    })

This is how I have connected with the mongooose to DB in app.js file and it is getting connected succeessfully. And I am using mongoose/mongoDB version as: 6.14.10

mongoose.connect(config.dbConnstring)
.then(()=>{
    console.log("connected to db");
})
.catch((err)=>{
    console.log("error:",err);
});

UPDATE:

const client = new MongoClient(uri);
  await client.connect();

  // Prereq: Create collections.

  await client
    .db('mydb1')
    .collection('foo')
    .insertOne({ abc: 0 }, { writeConcern: { w: 'majority' } });

  await client
    .db('mydb2')
    .collection('bar')
    .insertOne({ xyz: 0 }, { writeConcern: { w: 'majority' } });

  // Step 1: Start a Client Session
  const session = client.startSession();

  // Step 2: Optional. Define options to use for the transaction
  const transactionOptions = {
    readPreference: 'primary',
    readConcern: { level: 'local' },
    writeConcern: { w: 'majority' }
  };

  // Step 3: Use withTransaction to start a transaction, execute the callback, and commit (or abort on error)
  // Note: The callback for withTransaction MUST be async and/or return a Promise.
  try {
    await session.withTransaction(async () => {
      const coll1 = client.db('mydb1').collection('foo');
      const coll2 = client.db('mydb2').collection('bar');

      // Important:: You must pass the session to the operations

      await coll1.insertOne({ abc: 1 }, { session });
      await coll2.insertOne({ xyz: 999 }, { session });
    }, transactionOptions);
  } finally {
    await session.endSession();
    await client.close();

  }
question from:https://stackoverflow.com/questions/65871355/why-i-am-getting-error-as-startsession-is-not-a-function-while-using-transaction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...