简体   繁体   中英

Unable to connect to Mongodb from Nodejs

I am trying to connect to Mongodb from my first node project.I am using Mongoose to achieve that. However, mongoose.connect() gives me MongoParseError error.

Complete error:

MongoParseError: options connections, models, events, __driver, options, _pluralize, schema, model, plugins, default, mongoose, cast, states, setdriver, set, get, createconnection, connect, disconnect, startsession, pluralize, deletemodel, modelnames, plugin, version, schematype, schematypes, virtualtype, types, query, document, objectid, isvalidobjectid, isobjectidorhexstring, syncindexes, decimal128, mixed, date, number, error, now, casterror, schematypeoptions, mongo, mquery, trusted, skipmiddlewarefunction, overwritemiddlewareresult are not supported

Below is the snippet of my code.

const express = require('express');
const app = express();

const mongoose = require('mongoose');

const dotenv = require('dotenv');
dotenv.config();

app.use(express.json());

//configure mongoose
mongoose.connect(
  process.env.MONGODB_URI,
  mongoose.set('strictQuery', true),
  (err) => {
    if (err) {
      console.log(`Error while connecting: ${err}`);
    } else {
      console.log('Connected to MongoDB');
    }
  }
);

app.use('/', (req, res) => {
  res.send('Welcome to Node js server');
});

app.listen(3001, () => {
  console.log('Node js server is up and running');
});

The strictQuery refers to Mongoose schemas

mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error(`Error while connecting: ${err}`));
);

mongoose.set('strictQuery', true);

You can set to false for now to remove the warning message and make your connection async and listen to it separately.

mongoose.set("strictQuery", false);

mongoose.connection.once("open", () => {
    console.log("Connected to MongoDB!");
})

async function startServer() {
    try {
        await mongoose.connect(process.env.MONGODB_URI);
    } catch (err) {
        console.log(`Error while connecting: ${err}`);
    }
}

startServer().then(() => {
    app.listen(PORT, () => {    //set up your PORT
        console.log(`app is running on port ${PORT}...`)
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM