Warning on Connecting to MongoDB with a Node server

后端 未结 5 1426
有刺的猬
有刺的猬 2021-02-01 03:16

Connecting with MongoDB native driver

I wrote following code to connect mongodb through native driver which has been install with npm install mongodb --save

相关标签:
5条回答
  • 2021-02-01 03:28

    Replace yourdbname with your variable or just link of your mongodb..

     mongoose.connect(yourdbname, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
      .then(console.log("mongodb connected successfully...."))
      .catch(err =>console.log(err));
    
    0 讨论(0)
  • 2021-02-01 03:33

    Check your mongo version

     mongo --version
    

    If you are using version >= 3.1.0 change you mongo connection file to ->

     MongoClient.connect("mongodb://localhost:27017/YourDB", {
       useNewUrlParser: true,
       useUnifiedTopology: true
     })
    

    For details about the useUnifiedTopology option added in 3.2.1, see https://github.com/mongodb/node-mongodb-native/releases/tag/v3.2.1

    0 讨论(0)
  • 2021-02-01 03:35

    I got the same error and resolved using the below template.

    var MongoClient = require('mongodb').MongoClient
    
    const client = new MongoClient(uri, {useUnifiedTopology: true});
    
    client.connect().then((client)=>{
        var db = client.db('db_name')
        db.collection('collection_name').find().toArray(function (err, result) {
            if (err) throw err
            console.log(result);
        })
    })
    

    This worked for me. and now it's not showing any DepricationWarning.

    0 讨论(0)
  • 2021-02-01 03:40

    My advice is to leave it as it is (maybe place a warning). The useUnifiedTopology: true option does not work correctly.

    More precisely, in the event of a loss of connection to the DBMS, it will never be restored. Current version 3.3.3 does not solve this problem.

    Check this

    0 讨论(0)
  • 2021-02-01 03:48

    I want to add to this thread that it may also have to do with other dependencies.

    For instance, nothing I updated or set for NodeJS, MongoDB or Mongoose were the issue - however - connect-mongodb-session had been updated and starting slinging the same error. The solution, in this case, was to simply rollback the version of connect-mongodb-session from version 2.3.0 to 2.2.0.

    UPDATE: The issue is now fixed in connect-mongodb-session@2.3.1.

    0 讨论(0)
提交回复
热议问题