2

I am trying to connect Mongoose with my nodejs environment but it is giving an unexpected error. Before I was able to connect with mongoose with the same commands, But for few days its giving error

index.js file

import express from 'express';
import mongoose from 'mongoose'; 
import User from './User.js';

const app = express() 
const port = 5050 
const connection_url ="mongodb+srv://admin:'passwordhere'@cluster0.hcbbvuo.mongodb.net/?retryWrites=true&w=majority";

app.use(express.json())

mongoose.connect(connection_url,{
    useNewUrlParser: true, 
    useUnifiedTopology: true,
    family: 4, }) 

mongoose.connection.on('connected',()=>{   console.log("Connected to DB") })


app.post('/user',(req,res)=>{
   console.log('Creating new user')   
   const u = { "name":"Yash", "email":"yash@gmail.com", "password":"yash", "wins":0,   "losses":0   }

  User.create(u,(err,data)=>{
    if(err)
    console.log(err)
    else
    console.log(data)   
  })   
})


app.listen(port,()=>{
    console.log('Listening on port :',port) })

userSchema file

import mongoose from 'mongoose';

const User = mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique:true },
  password: { type: String, required: true },
  wins: { type: Number,default:0},
  losses: { type: Number,default:0},
});

export default mongoose.model('User',User)

Error

/home/yash/Desktop/VS code workspace/projects/node_modules/mongoose/lib/connection.js:824
  const serverSelectionError = new ServerSelectionError();
                               ^

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
    at NativeConnection.Connection.openUri (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/connection.js:824:32)
    at /home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/index.js:381:10
    at /home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/index.js:1234:10)
    at Mongoose.connect (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/index.js:380:20)
    at file:///home/yash/Desktop/VS%20code%20workspace/projects/crisscross-backend/index.js:12:10
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(3) {
      'ac-neif60o-shard-00-00.hcbbvuo.mongodb.net:27017' => ServerDescription {
        address: 'ac-neif60o-shard-00-00.hcbbvuo.mongodb.net:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 43667453,
        lastWriteDate: 0,
        error: null,
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      },
      'ac-neif60o-shard-00-01.hcbbvuo.mongodb.net:27017' => ServerDescription {
        address: 'ac-neif60o-shard-00-01.hcbbvuo.mongodb.net:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 43667454,
        lastWriteDate: 0,
        error: null,
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      },
      'ac-neif60o-shard-00-02.hcbbvuo.mongodb.net:27017' => ServerDescription {
        address: 'ac-neif60o-shard-00-02.hcbbvuo.mongodb.net:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 43667454,
        lastWriteDate: 0,
        error: null,
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'atlas-ap0orn-shard-0',
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

Few things :

  1. I have put '0.0.0.0/0' as IP in the network access on the mongoose, so its not the problem with IP

  2. I tried to put the driver code that mongoose gives to connect with the app

       const uri = "mongodb+srv://admin:<password>@cluster0.hcbbvuo.mongodb.net/?retryWrites=true&w=majority";
       const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
       client.connect(err => {
         const collection = client.db("test").collection("devices");
         // perform actions on the collection object
         client.close();
       });
    
    

Instead of mongoose.connect It has worked but when calling POST or GET request to create user or get any data it is giving this error

Error

MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:153:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
  • Have you already tried restarting the driver after changing config? Normally after whitelistening 0.0.0.0 you should be able to connect from external networks. – AidenDean Oct 21 '22 at 09:02
  • Yes I have. I tried making new DB also. I think its a problem in latest version of mongoose I will try installing older version once – YASH NIRMAL Oct 22 '22 at 03:43

1 Answers1

0

Try to remove useNewUrlParser: true and useUnifiedTopology: true from the connection config.

Starting with Mongoose v6+, these options are deprecated and will throw the error.

Try only with connection string, without the additional configs:

mongoose.connect(connection_url); 
NeNaD
  • 18,172
  • 8
  • 47
  • 89