简体   繁体   中英

nodejs not connecting to mongodb cloud server

I am trying to access mongodb(Atlas) yet not successful. on mongodb cloud the database name is star and the collection name is clc . However, I am getting cannot read property of null error message

const MongoClient = require('mongodb').MongoClient;


const uri = "mongodb+srv://daww:<PASSWORD>@cluster0-fmmcx.mongodb.net/test?retryWrites=true"
MongoClient.connect(uri, function(err, client) {
   if(err) {
        console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
   }
   console.log('Connected...');
   const collection = client.db("star").collection("clc");

   client.close();
});

I am getting the following error.

 const collection = client.db("star").collection("clc");
                             ^
TypeError: Cannot read property 'db' of null

Update : I updated the url as follows

const uri = "mongodb://daww:pass@cluster0-shard-00-00-fmmcx.mongodb.net:27017/star?retryWrites=true"

Now im getting this error

Error occurred while connecting to MongoDB Atlas...
 { MongoNetworkError: connection 0 to cluster0-shard-00-00-fmmcx.mongodb.net:27017 closed
    at Socket.<anonymous> (/Users/th/Desktop/main/node_modules/mongodb-core/lib/connection/connection.js:276:9)
    at Object.onceWrapper (events.js:273:13)
    at Socket.emit (events.js:182:13)
    at TCP._handle.close (net.js:606:12)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }
Connected...
/Users/th/Desktop/main/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
      throw err;
      ^

  TypeError: Cannot read property 'db' of null

Several things wrong here. First of all, client is null so in this case err should be defined, it should log out an error message. Also make sure to return if an error is defined:

if(err) {
    return console.log('Error occurred while connecting to MongoDB Atlas...\n',err);
}

Second MongoClient's connect callback is defined as follows

this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.

So why is it a db object and not a client instance? That is because connect uses the connection URL syntax as defined here

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

which includes the database name in the connection string.

If you want a client connection use MongoClient.open

Try to add IP Whitelist.

Go to your Clusters -> Security -> IP Whitelist -> on the right you will see ADD IP ADDRESS, click on it then click on ADD CURRENT IP ADDRESS.

Note that this will limit your db access to your IP only.

You should use this pattern, i used before for connection MongoDB server.

// Mlab Mongoose setup
const dbadd = require("./helpers/keys").mongoURI;
mongoose.connect(dbadd);
mongoose.Promise = global.Promise;
const db = mongoose.connection;

db.on("error", console.error.bind(console, "MongoDB connection error"));

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