Encountering difficulty when attempting to reference the `db.startSession()` method in Mongoose for MongoDB

Every time I attempt to reference db.startSession(), an error message saying

db.startSession() is not a function
pops up. I checked the console.log and found that the logged variable of db is shown below. Why am I unable to access startSession()?

connection

module.exports.db = mongoose
    .createConnection(process.env.DATABASE, { 
        useNewUrlParser: true, 
        useFindAndModify: false,
        useUnifiedTopology: true, 
        useCreateIndex: true
    }
);

controller

const db = require('./connection');

const session = db.startSession();
session.startTransaction();

logged variable db

{
  db: NativeConnection {
    base: Mongoose {
      connections: [Array],
      models: [Object],
      modelSchemas: [Object],
      options: [Object],
      _pluralize: [Function: pluralize],
      plugins: [Array]
    },
    collections: {},
    models: {},
    config: { autoIndex: true },
    replica: false,
    options: null,
    otherDbs: [],
    relatedDbs: {},
    states: [Object: null prototype] {
      '0': 'disconnected',
      '1': 'connected',
      '2': 'connecting',
      '3': 'disconnecting',
      '99': 'uninitialized',
      disconnected: 0,
      connected: 1,
      connecting: 2,
      disconnecting: 3,
      uninitialized: 99
    },
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: false,
    _connectionOptions: {
      useNewUrlParser: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
      useCreateIndex: true,
      promiseLibrary: [Function: Promise]
    },
    client: MongoClient {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      s: [Object],
      topology: [ReplSet],
      [Symbol(kCapture)]: false
    },
    name: null,
    '$initialConnection': Promise { [Circular] },
    db: Db {
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      s: [Object],
      serverConfig: [Getter],
      bufferMaxEntries: [Getter],
      databaseName: [Getter],
      [Symbol(kCapture)]: false
    }
  }
}

Answer №1

If you want to use transactions in mongoose, you must follow these steps:

Important: To use transactions, you need a replica MongoDB configuration. Convert a standalone database to a Replica Set and include retryWrites: false as an argument in the mongoose.createConnection() method.

To connect to mongoose:

      await mongoose.connect(`mongodb://localhost/namedb`, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        retryWrites: false
      });
const mongoose = require("mongoose");

const sess = await mongoose.startSession();
sess.startTransaction(); 
await teacher.save({ session: sess }); // execute a query
student.messages.push(); // perform some action
await student.save({ session: sess }); //// execute a query
await sess.commitTransaction();

If you want to use a replica set on localhost, you need to stop the mongod service and run the following code:

mongod --port 27017 --dbpath C:\data\rs1 --replSet m101 --bind_ip localhost

C:\data\rs1 is the data storage path.

 rs.initiate()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming text to numbers in JSON with JavaScript

Below is the JSON data that I have: { "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } } I am looking to extract the Month and Year values from both StartDate and EndDat ...

React componentDidUpdate triggers multiple API calls upon state change without limit

I'm currently diving into the world of Class Components for the first time, and I've encountered a puzzling issue involving an infinite loop. Here's how my initial state is set up: this.state = { selectedYear: null, error: nul ...

A guide on converting HTML and CSS to a PDF file using JavaScript

I'm facing a challenge where I need to create a custom quote in pdf using data retrieved in JavaScript and sent in HTML. However, the issue is that no library supports CSS for the PDF generation process. After some research, I came across HTML2CANVAS ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

Why does the code require the use of window when the Javascript error object is not functioning properly?

I'm struggling to grasp the distinction between var maxResult = window.max(maxValInt1, maxValInt2); which functions properly, and var maxResult = max(maxValInt1, maxValInt2); which gives an error "object is not a function". Why do I have to inclu ...

Having trouble with running the command "npx create-nuxt-app <project-name>"?

When attempting to create a Nuxt.Js app using npx, I encountered the error shown in the image below. https://i.sstatic.net/fnQT6.png ...

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

What is the best way to convert a table into a JSON string, especially when the table contains a dropdown menu using <select>?

I am currently working on a project where I need to extract selected data from a table using JSON. My goal is to populate an array with the extracted data and then push it into a SharePoint list. However, my current implementation pulls all the data from t ...

Insert JavaScript code into the head of the document (including the complete script code)

I am looking to insert a script in the head section of a website so that the target HTML appears as follows: <head><script type="text/javascript">*some code...*</script></head>. This particular script works perfectly: var head = d ...

Creating HTML dynamically upon page load with the use of JavaScript

I have a project where I need to create a small block of JavaScript that can be embedded in various websites' home pages. This script will automatically call a URL when visitors hit the home page, collecting specific statistics and returning a small i ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...

Out of the blue div, could you lend your assistance?

I have a code that displays 5 random images with corresponding text. My challenge is that I want to separate the text into another div so that I can add another function to it, while still keeping the images random with their corresponding text. <scr ...

Finding the smallest value for each day in MongoDB using Mongoose

I have a collection in my MongoDB database called measured_data that includes entries for each day containing the fields measured_at and value. I am looking for a way to use Mongoose to find the lowest value recorded for each day. Any insights or suggest ...

Ways to utilize a React custom hook that returns a value within the useEffect hook?

I'm dealing with a custom hook that returns a value based on the parameters it receives. In order to update this value dynamically, I attempted to use useEffect but encountered issues as the hook cannot be called within it. How can I work around this ...

Extract the value from JSON data

I am faced with the challenge of extracting the value of slug from each child in a JSON dataset. The issue lies in the fact that I cannot predict how many children will be generated whenever new data is received. The generation of nested children is dynam ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

Guidelines on concealing the parent component while the child component is loading in Angular 2

In my latest project, the view setup is as follows: https://i.sstatic.net/VxJ9U.png Upon page load, the Parent Item Description should be visible while the Selected sub item description remains hidden. When a Sub Item x is selected, the Parent Item Desc ...

Ensure the main checkbox is selected using jQuery

Currently, I am in the process of developing a JavaScript function that will automatically mark a parent checkbox if its child checkbox is checked (only if it's not already marked). For this task, I'm utilizing jQuery. Below is a snippet of my HT ...

optimizing URLs in express js

I have developed a route that retrieves a user's complete details from the database (MongoDB). Router router.get('/user/:userid/:name', getUrl, function(req, res, next) { User.findOne({_id: req.params.userid}) .exec(function(err, user) ...