简体   繁体   中英

I am trying to connect mongodb server with node

I tried to connect my mongo cluster with my local server but this error keeps on showing up. I am following a tutorial and it seems to work fine for the tutor but this error comes for me. I have provided the error screenshot below.

Error which comes up

The src has been provided

 const express = require('express'); const env = require('dotenv'); const app = express(); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); //routes const userRoutes = require('./routes/user'); //constants env.config(); //mongodb connect //mongodb+srv://root:<password>@cluster0.9ylhh.mongodb.net/myFirstDatabase?retryWrites=true&w=majority mongoose.connect( `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}@cluster0.9ylhh.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true } ).then(() => { console.log('Database connected'); }); //middleware app.use(express.urlencoded({ extended: true})); app.use(express.json()); app.listen(process.env.PORT, () => { console.log(`server is running on port ${process.env.PORT}`); });

I also did create a .env file with the credentials details and stuff

I tried to make a comment instead of an answer, but I don't have enough reputation.

If the error is authentication, maybe you have a problem with your credentials.

Does your username or password have any of these chars? : / ? # [ ] @
If they do, you'll have to URI encode them like so:

${encodeURIComponent(process.env.MONGO_DB_USER)}

${encodeURIComponent(process.env.MONGO_DB_PASSWORD)}

More info here: https://docs.mongodb.com/manual/reference/connection-string/#examples

BTW: You forgot the env part on your ${process.MONGO_DB_PASSWORD} .

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