[英]Connection to MongoDB with Mongoose not working
I created a new mongoDB database and used Express generator to create my backend folder.我创建了一个新的 mongoDB 数据库并使用 Express 生成器来创建我的后端文件夹。 I want to make a connection to my mongoDB database using Mongoose.
我想使用 Mongoose 连接到我的 mongoDB 数据库。
I tried this:我试过这个:
const mongoose = require('mongoose');
var options = {
connectTimeoutMS: 5000,
useNewUrlParser: true,
};
mongoose.connect('mongodb+srv://UserName:<password>@cluster1-hxnnz.azure.mongodb.net/CollectionName?retryWrites=true&w=majority',
options,
function(err) {
if (err) {
console.log(err);
} else {
console.info('connection ok');
}
}
);
module.exports = mongoose;
Username
Password
and CollectionName
are correctly replaced, I use the link that mongodb gives me to make a connection. Username
Password
和CollectionName
已正确替换,我使用 mongodb 给我的链接进行连接。 Nothing is happening, no console log is displayed.什么都没有发生,没有显示控制台日志。 I tried other solutions of the forum and the code given by mongoose but without success
我尝试了论坛的其他解决方案和猫鼬给出的代码但没有成功
Thanks for the help.谢谢您的帮助。
This code works fine.这段代码工作正常。 I think this is your DB file(db.js) you just need to import it in your starter file (app.js) require('./db');
我认为这是您的 DB 文件(db.js),您只需将其导入您的启动文件(app.js) require('./db');
const mongoose = require('mongoose');
var options = {
connectTimeoutMS: 5000,
useNewUrlParser: true,
};
mongoose.connect('mongodb+srv://UserName:<password>@cluster1-hxnnz.azure.mongodb.net/CollectionName?retryWrites=true&w=majority',
options,
function(err) {
if (err) {
console.log(err);
} else {
console.info('connection ok');
}
}
);
module.exports = mongoose;
and for your security purpose separate MongoDB's link from that file并且为了您的安全目的,将 MongoDB 的链接与该文件分开
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.