代码
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://userName:password@saichaitanyacluster-1m22k.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
client.close();
});
答案 0 :(得分:0)
在致电client.db()
之前,应添加检查以确认连接中没有错误。连接代码应如下所示:
// ...Everything that was here before
client.connect(err => {
if (err) {
console.log("There was an error connecting to the database");
// Any other logic that you want to use to handle the error should live here.
// Add a return statement to help avoid executing
// the code below that relies on a successful connection
return;
}
const collection = client.db("test").collection("devices");
client.close();
});
我希望这会有所帮助。