我创建了一个新的mongoDB数据库,并使用Express生成器创建了我的后端文件夹。我想使用Mongoose与我的mongoDB数据库建立连接。
我尝试过:
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
和CollectionName
已正确替换,我使用mongodb给我的连接建立了链接。什么也没发生,没有控制台日志显示。我尝试了论坛的其他解决方案以及猫鼬给出的代码,但没有成功
感谢您的帮助。
此代码可以正常工作。我认为这是您的数据库文件(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;
为了您的安全起见,将MongoDB的链接与该文件分开