与Mongoose不能正常连接到MongoDB

问题描述 投票:0回答:1

我创建了一个新的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 PasswordCollectionName已正确替换,我使用mongodb给我的连接建立了链接。什么也没发生,没有控制台日志显示。我尝试了论坛的其他解决方案以及猫鼬给出的代码,但没有成功

  • 猫鼬:5.9.4,
  • express:4.16.1,

感谢您的帮助。

node.js mongodb express mongoose database-connection
1个回答
1
投票

此代码可以正常工作。我认为这是您的数据库文件(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的链接与该文件分开

© www.soinside.com 2019 - 2024. All rights reserved.