简体   繁体   中英

How to connect mongodb atlas with nodejs

I'm trying to connect a mongodb atas database i've just created with my nodejs program but I got this error :

Error: Invalid mongodb uri "mongodb+srv://loginr:aqpass5@cluster0-ymz55.mongodb.net/barcode?retryWrites=true". Must begin with "mongodb://"

export default {
    "mongoUrl": "mongodb+srv://user:password@cluster0-ymz55.mongodb.net/barcode?retryWrites=true", 
}
import mongoose from 'mongoose';
import config from '../config/index';

mongoose.Promise = global.Promise;

const connectToDb = async () => {
    try {
        await mongoose.connect(config.mongoUrl, { useMongoClient: true });
        logger.info('Connected to mongo!!!');
    }
    catch (err) {
        console.log(err);
        logger.error('Could not connect to MongoDB');
    }
}

export default connectToDb;

Depending on your structure... I have the 'myurl'-file in the folder 'setup' and the index.js file outside that map.:

In the myurl-file:

module.exports = {
mongoURL:"mongodb+srv://username:Password@cluster0-8htmv.mongodb.net/test?retryWrites=true&w=majority"};

Make sure you have the password right with the right user.

In the 'index.js'-file:

const db = require('./setup/myurl').mongoURL; //directs to your other js-file

mongoose
.connect(db,**{useNewUrlParser: true, //this part is fairly new
    useUnifiedTopology: true}**)
.then(() => console.log("Success"))
.catch(err => console.log(err)); 

Good luck

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