Node.js 向mongodb添加数据时出错

Node.js 向mongodb添加数据时出错,node.js,mongodb,express,Node.js,Mongodb,Express,我试图在mongodb中添加数据,但每次向api发出post请求时都会出错 我在这里分享代码 var MongoClient = require("mongodb").MongoClient; var url = "mongodb+srv://******:***********@cluster0-bxzzc.mongodb.net/auth?retryWrites=true&w=majority"; exports.addUser = async (req, res, next)

我试图在mongodb中添加数据,但每次向api发出post请求时都会出错 我在这里分享代码

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");
    });
}
var MongoClient=require(“mongodb”).MongoClient;
变量url=
“mongodb+srv://*********:*********@cluster0 bxzzc.mongodb.net/auth?retryWrites=true&w=mailty”;
exports.addUser=async(请求、恢复、下一步)=>{
MongoClient.connect(url)
.then(函数(db){
//  {
res.send(result.ops[0]);
})
.catch(错误=>{
res.send(“数据库中的故障”);
});
})
.catch(函数(err){
控制台日志(err);
res.send(“错误”);
});
}
所以,每当我发出请求时,控制台中就会出现错误

TypeError:db.collection不是函数

另外,我是新手,所以我是否处理过错误更正,比如在向mongodb添加数据时出现错误时处理错误的一个捕获,以及在api中出现错误时处理错误的另一个外部捕获检查此答案:检查此答案: