M H*_*lal 10 mongodb node.js express mongodb-atlas
我正在尝试通过Mongoose.connect()连接mongoDB Atlas上的集群,但每次我尝试连接时都会遇到异常"MongoError:身份验证失败"我知道MongoDB Atlas是新的mongo,因为服务可能不是由猫鼬支持了吗?
小智 10
MongoError:身份验证失败- 这意味着您的姓名或密码或 dbname 不正确 -
uri 样本 -
const uri =
"mongodb+srv://<username>:<password>@firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";
Run Code Online (Sandbox Code Playgroud)
假设用户名是 - najim & 密码是1234 & dbname 是pets(注意 - 默认 dbname 是 test 但你可以写任何你想要的)那么我的 uri 将与上面的凭据 -
const mongoAtlasUri =
"mongodb+srv://najim:1234@firstcluster.4rc4s.mongodb.net/pets?retryWrites=true&w=majority";
Run Code Online (Sandbox Code Playgroud)
与 Moongoose 建立联系
try {
// Connect to the MongoDB cluster
mongoose.connect(
mongoAtlasUri,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log(" Mongoose is connected")
);
} catch (e) {
console.log("could not connect");
}
Run Code Online (Sandbox Code Playgroud)
小智 7
const mongoAtlasUri =
"mongodb+srv://<username>:<password>@firstcluster.4rc4s.mongodb.net/<dbname>?retryWrites=true&w=majority";
try {
// Connect to the MongoDB cluster
mongoose.connect(
mongoAtlasUri,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log(" Mongoose is connected"),
);
} catch (e) {
console.log("could not connect");
}
const dbConnection = mongoose.connection;
dbConnection.on("error", (err) => console.log(`Connection error ${err}`));
dbConnection.once("open", () => console.log("Connected to DB!"));
Run Code Online (Sandbox Code Playgroud)
此相关文章中的答案是正确的。你应该:
使用Atlas提供的连接字符串,并将其提供给
mongoose.connect(uri);
Run Code Online (Sandbox Code Playgroud)小智 5
try {
mongoose.connect( uri, {useNewUrlParser: true, useUnifiedTopology: true}, () =>
console.log("connected"));
}catch (error) {
console.log("could not connect");
}
Run Code Online (Sandbox Code Playgroud)
这个效果很好,试试吧
| 归档时间: |
|
| 查看次数: |
14959 次 |
| 最近记录: |