Home > Software design >  Node.js app cannot connect to MongoDB Atlas cluster
Node.js app cannot connect to MongoDB Atlas cluster

Time:12-16

error: server running in development mode on port 5000 errorMongoParseError: option usecreateindex is not supported [nodemon] app crashed - waiting for file changes before starting...

db.js

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
      useCreateIndex: true,
    });
    console.log(`MongoDB connected :${conn.connection.host}`);
  } catch (error) {
    console.error(`error${error}`);
    process.exit(1);
  }
};
export default connectDB;

server.js

import express from "express";
import dotenv from "dotenv";
import connectDB from './config/db.js'
import products from './data/products.js'


dotenv.config();

connectDB()

const app = express();

app.get("/", (req, res) => {
  res.send("api is running... ");
});

app.get("/api/products", (req, res) => {
  res.json(products);
});

app.get("/api/products/:id", (req, res) => {
  const product = products.find(p => p._id === req.params.id);
  res.json(product);
});


const PORT = process.env.PORT || 5000

app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

CodePudding user response:

No More Deprecation Warning Options

Mongoose docs

useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.

db.js

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      // useUnifiedTopology: true, <-- no longer necessary
      // useNewUrlParser: true, <-- no longer necessary
      // useCreateIndex: true, <-- no longer necessary
    });
    console.log(`MongoDB connected :${conn.connection.host}`);
  } catch (error) {
    console.error(`error${error}`);
    process.exit(1);
  }
};
export default connectDB;
  • Related