猫鼬中的FindOne返回未定义

时间:2020-07-10 14:21:08

标签: node.js database mongodb express mongoose

当使用Find方法将所有数据整合到数据库中时,其中会出现一个标题为:“ day1”的对象,但是当我执行findOne操作时,我将得到未定义的输出。 请帮助我。

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

2 个答案:

答案 0 :(得分:1)

改为使用以下查询

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

答案 1 :(得分:0)

这是因为您将回调与Promise混在一起了。

如果您将使用回调方法,则可以使用以下代码:

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
})

如果要使用promise方法:

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