【问题标题】:FindOne in mongoose returns undefined猫鼬中的 FindOne 返回未定义
【发布时间】:2020-07-11 10:07:07
【问题描述】:

当我使用 Find 方法整理数据库中的所有数据时,其中存在一个 Title:'day1' 的对象,但是当我执行 findOne 操作时,我得到未定义的输出。 请帮帮我。

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

【问题讨论】:

  • 使用Promise时,第一个参数是你的payload(err是结果)

标签: node.js database mongodb express mongoose


【解决方案1】:

改用以下查询

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

【讨论】:

  • 您只是在使用回调而不是 Promise 模式。这会发生什么变化?
【解决方案2】:

那是因为你把回调和 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

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 2019-02-13
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多