【问题标题】:mongoDB with nodejs return data带有nodejs的mongoDB返回数据
【发布时间】:2020-01-17 22:48:33
【问题描述】:

我有我自己的类和方法调用 findByIdDate() 当我找到数据然后在 db.collection() 内部我会得到结果,但如果我想从我自己的方法返回该数据,它将返回未定义。 有人可以提供我如何获取数据的示例吗?我一直在寻找,但我找不到这个问题的任何答案。我是节点和表达的新手 我的方法

findByIdDate(){
    let data = this.db.collection('journal').find({date: this.Date}).toArray((err, result) => {
        if(err){return console.log(err)}
        console.log(result) // I have data
        return result
    })
    return data
}

在我的其他文件中我是这样使用的

app.post('/id', (req, res) => {

  const DIARY = new diary('new', '16 January 2020', db)
  let result = DIARY.findByIdDate()
  console.log(result) // undefined 

});

【问题讨论】:

  • 你能提取并提供一个minimal reproducible example吗?另外,只是想知道,您给toArray 的闭包是否是异步执行的,而toArray() 没有返回任何内容?我不熟悉 JS MongoDB API,但异步调用在 JS 世界中并非闻所未闻。
  • findByIdDate() 返回之前,您可能是 console.logging result。有几种方法可以处理这个问题,最现代的是使用async/await。这应该会引导您朝着正确的方向前进。

标签: node.js mongodb express


【解决方案1】:

最好去掉回调函数,将函数async/await设为:

async findByIdDate(){
    try {
        let data = await this.db.collection('journal')
            .find({date: this.Date})
            .toArray() // returns a promise which can be 'awaited'
        console.log(data)
        return data
    } catch (err) {
        console.error(err)
        throw err
    }
}

并在您的路线中使用它作为

app.post('/id', async (req, res) => {
    try {
        const DIARY = new diary('new', '16 January 2020', db)
        let result = await DIARY.findByIdDate()
        console.log(result) 
    } catch(err) {
        console.error(err)
    }    
})

【讨论】:

  • 绝对正确。让我补充一下:原因是对 MongoDB 的调用是异步的。并且在 find 调用之外的原始代码中的 return 语句被同步调用。它以undefined 返回数据,因为在调用它时,数据仍然是undefined。之前的语句还没有返回任何东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多