node.js - Unable to Connect with MongoDB Atlas from Local Node App
问题描述
I have created a cluster on atlas and attempted to connect using my node app and log the connection status with mongoose. I have whitelisted my ip and set everything up properly but I keep getting UnhandledPromiseRejectionWarning
.
Here's my code for db.js
. Error throws on 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;
In server.js
file, I just called the function like db_connect();
after importing with commonjs module.
Any help will be appreciated as I can't find what the issue is. Thanks.
解决方案
You can also try this in case the solution does not work:
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;
I have just tested this solution in my computer, and it works!
But, in case none of that works, can send you how I do the connection.
推荐阅读
- macos - 如何在 macos 上实现虚拟文件系统?
- javascript - 未捕获的 ReferenceError:未定义的参数
- c - 为什么'a'的地址不是使用*(&a)打印'a'的第一个元素的值?
- mongodb - 在 AWS Lambda 函数中连接到 MongoDB 数据库时出现“任务超时...”
- windows - PowerShell Invoke-WebRequest 产生 422 不可处理的实体?
- c++ - 如何使用 openSSL C++ 以 PEM 格式存储 Diffie HellMan 对象的密钥
- mysql - 在 mysql 中用作索引的 uuid 如何在 b-tree 中排序?
- ruby-on-rails - 为什么 Rails 会给我这个 NoMethodError?
- node.js - 使用 http 时,req.body 是 empy {}。在 angular 和 node.js 中发布
- excel - 运行时返回空白的函数未通过 2 个值之间的检查