我在尝试连接 Cloud Atlas MongoDB 时遇到问题。我能够连接到我的本地 MongoDB,但是在尝试连接 Cloud Atlas MongoDB 时,我遇到了这个问题。有谁知道错误是什么意思?以及如何解决。
DBConnection.js
const mongoose = require("mongoose");
require("dotenv").config();
const CONNECTION_URL = process.env.MONGODB_URI_Saket;
mongoose.connect(CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
process.on("SIGINT", async () => {
await mongoose.connection.close();
process.exit(0);
});
mongoose.connection.on("connected", () => {
console.log("Mongo has connected succesfully");
});
mongoose.connection.on("reconnected", () => {
console.log("Mongo has reconnected");
});
mongoose.connection.on("error", (error) => {
console.log("Mongo connection has an error", error);
mongoose.disconnect();
});
mongoose.connection.on("disconnected", () => {
console.log("Mongo connection is disconnected");
});
Server.js
const express = require("express");
const cors = require("cors");
const logger = require("morgan");
require("dotenv").config();
const bodyParser = require("body-parser");
require("./database/mongodbinit");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(express.json());
app.use(logger("dev"));
const allroutes = require("./routes/index");
app.use(allroutes);
app.get("/", (req, res, next) => {
res.send("hello world");
});
/** catch 404 and forward to error handler */
app.use("*", (req, res) => {
return res.status(404).json({
success: false,
message: "API endpoint doesnt exist",
});
});
app.use(function (err, req, res, next) {
if (err.message) {
res.status(400).send(err.message);
} else {
err.message = "internal server error";
res.status(500).send(err.message);
}
});
const PORT = process.env.Port || 8080;
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
});
MongoDB_URI
MONGOURI=mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.2sn1f.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority
我已在 .env 中为 DB_USER、DB_PASS 和 DB_NAME 分配了值。
答案 0 :(得分:0)
您无法访问 .env 文件中的 process.env
。
您应该使用用户名和密码编写完整的 url。
.env 用于存储敏感数据,因此可以将包含凭据的数据库的完整 url 放入其中。
另一种方法是:
const options = {
db: { native_parser: true },
server: { poolSize: 5 },
replset: { rs_name: 'yourSetName' },
user: 'yourUserName',
pass: 'yourPassword',
promiseLibrary: global.Promise
}
mongoose.connect(uri, options).then(conn=>{}).catch(err=>{});