mongodb MongooseError:Model.create()不再接受回调函数如何使用async await?

wdebmtf2  于 2023-04-20  发布在  Go
关注(0)|答案(2)|浏览(262)

app.post('/ contactForm',function(req,res){

Contact.create({
        name: req.body.name,
        phone: req.body.phone
    },  function(err, newContact){
        if(err){
            console.log(err, 'error in connectiong');
            return;
        }
        console.log("*******", newContact);
        return   res.redirect('back');
    })

})
/home/ganesh/Web Dev/CN Web Dev/HTML/basics/Nodejs Workspace/contact_list/node_modules/mongoose/lib/model.js:2771 throw new MongooseError('Model.create()不再接受回调');

b1uwtaje

b1uwtaje1#

应该是
app.post('/ contactForm',function(req,res){

Contact.create({
        name: req.body.name,
        phone: req.body.phone
    }).then( (newContact) => {
        console.log("*******", newContact);
        return   res.redirect('back');
    }).catch((err) => {
        console.error(err);
    })

})

7d7tgy0s

7d7tgy0s2#

https://mongoosejs.com/docs/migrating_to_7.html#dropped-callback-support

exports.createUser = async (req, res) => {
  const { firstName, phone } = req.body;

  try {
    const user = await User.create({
      firstName,
      phone,
    });
    return res.redirect("back");
  } catch (err) {
    return console.log(err, "error in connectiong");
  }
};

相关问题