简体   繁体   English

mongoDB 与 nodejs 返回数据

[英]mongoDB with nodejs return data

I have my own class and method call findByIdDate() When I find the data then inside of db.collection() I will get result but if I want to return that data from my own method it will come back undefined.我有自己的类和方法调用 findByIdDate() 当我在 db.collection() 中找到数据时,我会得到结果,但如果我想从我自己的方法中返回该数据,它将返回未定义。 Could someone provide me example how to get the data please?有人可以为我提供如何获取数据的示例吗? I have been searching but I can not find any answers to this problem.我一直在搜索,但我找不到这个问题的任何答案。 I'm new to node and express My Method我是节点的新手并表达了我的方法

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
}

in my other file I use it like this在我的另一个文件中,我像这样使用它

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

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

});

It would be best to do away with callback functions and make the function async/await as:最好取消回调函数并使函数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
    }
}

And use it in your route as并在您的路线中使用它作为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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