'Why can't I connect to mongoDB atlas?
I am new in MongoDB, all my life I used MySQL.
I have created an account in atlas, set the IP to my IP and created a user and saved the password.
here is my code, why doesn't it work?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoPractice = require('./mongo');
const app = express();
app.use(bodyParser.json());
app.post('/products', mongoPractice.createProduct);
app.get('/products');
app.listen(3000);
and the mongo.js:
const MongoClient = require("mongodb").MongoClient;
const url =
"mongodb+srv://idan:<85IwoSzeQssHMzLN>@cluster0.tpejv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const createProduct = async (req, res, next) => {
const newProduct = {
name: req.body.name,
price: req.body.price,
};
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db();
const result = db.collection("products").insertOne(newProduct);
} catch (error) {
return res.json(error);
}
client.close();
res.json(newProduct);
};
const getProducts = async (req, res, next) => {};
exports.createProduct = createProduct;
exports.getProducts = getProducts;
the POSTMAN output:
Solution 1:[1]
Your ip may have changed, (check if the current ip address has information "(includes your current IP address)"
. For testing(!) you can add address 0.0.0.0/0 to the whitelist - it means every ip will be accepted - this solution is good for beginners
Solution 2:[2]
- Firstly check you connection link from mongodb connect
- Check username, password again
- You can change password and try again
Solution 3:[3]
In mongo.js
You need to remove "< >" around the password.
const url = "mongodb+srv://idan:**85IwoSzeQssHMzLN**@cluster0.tpejv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jakub Kurdziel |
Solution 2 | Lee Taylor |
Solution 3 |