1

I am trying to add data in mongodb but getting error everytime i make a post request to api here i share the code

var MongoClient = require("mongodb").MongoClient;
var url =
  "mongodb+srv://******:***********@cluster0-bxzzc.mongodb.net/auth?retryWrites=true&w=majority";

exports.addUser = async (req, res, next) => {
  MongoClient.connect(url)
    .then(function(db) {
      // <- db as first argument
      db.collection("user")
        .insertOne({
          name: req.body.name,
          password:req.body.password
        })
        .then(result => {
          res.send(result.ops[0]);
        })
        .catch(err => {
          res.send("failure in db");
        });
    })
    .catch(function(err) {
      console.log(err);
      res.send("error");
    });
}

so whenever i am making a request i am getting error in console that

TypeError: db.collection is not a function

and also i am new to express so have i handled error correct like one catch for handling error if we get some error while adding data to mongodb and another outer catch if we have something wrong in our api

Naruto
  • 53
  • 8
  • check this answer: https://stackoverflow.com/questions/47662220/db-collection-is-not-a-function-when-using-mongoclient-v3-0 – Mohamed Magdy Mar 28 '20 at 15:46

0 Answers0