使用 Mongoose 连接到 MongoDB 不工作

Connection to MongoDB with Mongoose not working

我创建了一个新的 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 给我的 link 进行连接。 什么都没有发生,没有显示控制台日志。我尝试了论坛的其他解决方案和猫鼬给出的代码但没有成功

感谢您的帮助。

这段代码工作正常。我认为这是你的数据库文件(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 的 link 与该文件分开