简体   繁体   中英

I am unable to connect my MongoDb with Vs code

I used MongoDb Atlas for my progrom, But I am unable to connect with database, Here I used Postman to perform different operation but whenever I send some request, Error will occured.

const mongoose = require('mongoose');

const Product = require('./modelss/product');

mongoose.connect('mongodb+srv://<UserName>:<Password>@cluster1.un9kapv.mongodb.net/?retryWrites=true&w=majority'
).then(() => {
    console.log('Connected to the database!')

}).catch(() => {
    console.log('Connection failed!')
});


const createProduct = async(req, res,next) => {
    const createdProduct = new Product({
        name: req.body.name,
        price: req.body.price
    });
    console.log(createdProduct);
    const result = await createProduct.save();
    res.json(result);
};

const GetProduct = async(req,res,next) => {
    const products = await Product.find().exec();
    res.json(products);
}

exports.createProduct = createProduct;
exports.GetProduct = GetProduct;

Before Sending any request from Postman it shows-: enter image description here

But After sending request -: enter image description here

  1. Try adding your IP Address to your mongoDB access panel or make it open access to all IP(only for development purposes).
  2. Replace "Username" and "Password" in mongoose.connect with your actual username and password for the database which you have made.

To debug such things you can catch the error and then console.log it out-

catch(e){
console.log(e)
}

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