简体   繁体   中英

FindOne in mongoose returns undefined

When im consoling all the data int he database using Find method, an object with Title:'day1' is present in it but when I perform findOne operation I get undefined as output. Please help me.

 Post.findOne({ Title: 'day1'}).then(function(err, result){console.log(result)});

Use the following query instead

Post.findOne({ Title: 'day1'},function(err,data)
{
  if(err)
    { res.send(err)}
  else if(data)
    {res.send(data)}
})

It is because you mixed up callback with Promise..

If you will use Callback method you can use the following code:

Post.findOne({Title: 'day1'}, (err, data) {
    if (err) {
      return res.status(404).send(err); // If there is an error stop the function and throw an error
    }
    res.status(200).send(data) // If there is no error send the data
})

If you are going to use the promise method:

Post.findOne({Title: 'day1'})
.then(data => res.status(200).send(data)) // Send data if no errors
.catch(err => res.status(404).send(err)) // Throw an error if something happens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM