TypeError: db.collection is not a function

后端 未结 18 2463
青春惊慌失措
青春惊慌失措 2020-11-27 03:09

I am trying to post data to database that I have created on mLab and I am getting this error but I don\'t know whats going wrong.I also have read previously asked question o

18条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 03:31

    Dont use database name in connection url:

    const mongo_url = 'mongodb://localhost:27017'
    

    Instead use below method:

    MongoClient.connect(mongo_url , { useNewUrlParser: true }, (err, client) => {
            if (err) return console.log(err)
            const  db =  client.db('student')
            const collection = db.collection('test_student');
            console.log(req.body);
            collection.insertOne(req.body,(err,result)=>{
                if(err){
                    res.json(err);
                }
                res.json(result);
            });
        });
    

提交回复
热议问题