mongoDB 与 nodejs 返回数据 [英] mongoDB with nodejs return data
问题描述
我有自己的类和方法调用 findByIdDate() 当我在 db.collection() 中找到数据时,我会得到结果,但如果我想从我自己的方法中返回该数据,它将返回未定义.有人可以为我提供如何获取数据的示例吗?我一直在搜索,但我找不到这个问题的任何答案.我是 node 和 express 的新手我的方法
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. 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
});
推荐答案
最好取消回调函数,使函数 async/await
为:
It would be best to do away with callback functions and make the function async/await
as:
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)
}
})
这篇关于mongoDB 与 nodejs 返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!