我在地图集上创建了一个集群,并尝试使用我的节点应用程序进行连接,并使用mongoose记录连接状态。我已将自己的IP列入白名单并正确设置了所有内容,但我不断收到UnhandledPromiseRejectionWarning
。
这是我的db.js
代码。错误引发mongooose.connect(url, opts)
。
const mongoose = require('mongoose');
const db_connect = async () => {
const conn_string = await mongoose.connect('mongodb+srv://devjoe:
<password_hidden_delibarately>@devcamper-gs1nb.mongodb.net/devcamper?retry
Writes=true&w=majority',
{
useCreateIndex: true,
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log(`connection string: ${conn_string.connection.host}`);
}
module.exports = db_connect;
在server.js
文件中,使用commonjs模块导入后,我刚刚调用了db_connect();
之类的函数。
任何帮助将不胜感激,因为我找不到问题所在。谢谢。
答案 0 :(得分:1)
如果解决方案不起作用,您也可以尝试以下方法:
const mongoose = require("mongoose");
const db_connect = () => {
try {
const conn_string = mongoose.connect(
"mongodb+srv://devjoe: <*****************>@devcamper-gs1nb.mongodb.net/devcamper?retry Writes=true&w=majority",
{
useCreateIndex: true,
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}
);
console.log(`connection string: ${conn_string.connection.host}`);
} catch {
console.log(`not connected to : ${conn_string.connection.host}`);
}
};
module.exports = db_connect;
我刚刚在计算机上测试了此解决方案,它可以工作!
但是,如果这些都不起作用,可以向您发送我如何进行连接。