简体   繁体   中英

Connection to MongoDB with Mongoose not working

I created a new mongoDB database and used Express generator to create my backend folder. I want to make a connection to my mongoDB database using Mongoose.

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. Nothing is happening, no console log is displayed. I tried other solutions of the forum and the code given by mongoose but without success

  • mongoose: 5.9.4,
  • express: 4.16.1,

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');

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM