Search code examples
node.jsmongodbmongoosecallback

mongoose code showing error of a call ack function


app.post ('/create_contact',function(req,res) 
{
  contact.create({
    name :req.body.name,
    phone:req.body.phone
  },function(err,newContact)
  {
    if(err){console.log('error in creating a contact!');
    return;}

  console.log('********',newContact);
  return res.redirect('back');
  });
});

Errors:

throw new MongooseError('Model.create() no longer accepts a callback');
          ^
MongooseError: Model.create() no longer accepts a callback

I tried this code but again showing error


Solution

  • You can solve it with async await

    app.post('/create_contact', async function (req, res) {
      try {
        const newContact = await contact.create(req.body);
        console.log('********', newContact);
        return res.redirect('back');
      } catch (err) {
        res.send('error in creating a contact!');
      }
    });