I'm trying to connect mongoDB to my web app but it shows following error

Listening on localhost:9000 D:\whatsapp\signal-backend\node_modules\mongodb\lib\connection_string.js:281 throw new error_1.MongoParseError(${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported); ^ MongoParseError: option usecreateindex is not supported at Object.parseOptions (D:\whatsapp\signal-backend\node_modules\mongodb\lib\connection_string.js:281:15) at new MongoClient (D:\whatsapp\signal-backend\node_modules\mongodb\lib\mongo_client.js:62:46) at D:\whatsapp\signal-backend\node_modules\mongoose\lib\connection.js:785:16 at new Promise () at NativeConnection.Connection.openUri (D:\whatsapp\signal-backend\node_modules\mongoose\lib\connection.js:782:19) at D:\whatsapp\signal-backend\node_modules\mongoose\lib\index.js:330:10 at D:\whatsapp\signal-backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5 at new Promise () at promiseOrCallback (D:\whatsapp\signal-backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10) at Mongoose._promiseOrCallback (D:\whatsapp\signal-backend\node_modules\mongoose\lib\index.js:1151:10) [nodemon] app crashed - waiting for file changes before starting…

Your code is broken. Paste your source code and we might be able to point out your mistake.

Welcome to the MongoDB Community Forums @shuence !

As @Jack_Woehr mentioned, we need more information to understand the error you are encountering. I suspect you may have an error in your connection string or are using an older version of Mongoose that does not support the options you are trying to set.

Please provide:

  • A snippet of code showing how you are creating the connection including your MongoDB connection string with any password or hostname details redacted

  • Versions of Mongoose and MongoDB Node.js driver being used

Regards,
Stennie

Here is my source code:

    //Creating an API

    // importing
    import express from "express";
    import mongoose from "mongoose";
    import Messages from "./dbMessages.js";
    import cors from "cors";

    //app config
    const app = express();
    const port = process.env.PORT || 9000;



    // middleware
    app.use(express.json());
    app.use(cors());

    // DB config
    const connection_url =
    "mongodb+srv://admin:shubham2323@cluster0.lbb8n.mongodb.net/<DbImUsing>?retryWrites=true&w=majority";
    mongoose.connect(connection_url, {
      useCreateIndex: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });

    // pusher
    const db = mongoose.connection;

    db.once("open", () => {
      console.log("DB connected");

      const msgCollection = db.collection("messagecontents");
      const changeStream = msgCollection.watch();

      changeStream.on("change", (change) => {
    console.log("A change occured", change);

    if (change.operationType === "insert") {
      const messageDetails = change.fullDocument;
      pusher.trigger("message", "inserted", {
        name: messageDetails.name,
        message: messageDetails.message,
        timestamp: messageDetails.timestamp,
        received: messageDetails.received,
      });
    } else {
      console.log("Error triggering Pusher");
    }
      });
    });

    // api routes
    app.get("/", (req, res) => res.status(200).send("hello world"));

    app.get("/messages/sync", (req, res) => {
      Messages.find((err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
      });
    });

    app.post("/messages/new", (req, res) => {
      const dbMessage = req.body;
      Messages.create(dbMessage, (err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(201).send(data);
    }
      });
    });

    // listen

    app.listen(port, () => console.log(`Listening on localhost:${port}`));

I’m using

“cors”: “^2.8.5”,
“express”: “^4.17.1”,
“mongoose”: “^6.0.0”

I assume you are just obfuscating your code here? Or does that string <DbImUsing> really appear in your connection string?

That error is solved but now I’m getting a new error
file:///D:/whatsapp/signal-backend/server.js:33
db.once(‘connect’, () => {
^

TypeError: Cannot read property 'once' of undefined
    at file:///D:/whatsapp/signal-backend/server.js:33:4
    at ModuleJob.run (node:internal/modules/esm/module_job:175:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
[nodemon] app crashed - waiting for file changes before starting...

Could you share how you fixed the initial issue please?

I managed to fix this issue by checking the mongodb version, I was using ver. 4.x.x when this error was happening. Downgrading to v3.6.10 resolved the issue. (I am using mongo with Nest.js and node-eventsourcing).

Means that

mongoose.connection is undefined. Which in turn means

does not do what you expect it to do. You might need to use await to suspend the rest of the code until the connection is really made.

I have the same problem, but when I downgraded to version@5 and it work perfectly.

2 Likes