【问题标题】:Export Value from Mongoose find function in NodeJs从 NodeJs 中的 Mongoose 查找函数导出值
【发布时间】:2022-02-20 06:45:33
【问题描述】:
我正在尝试使用 nodejs 构建一个应用程序。我正在使用 Mongoose 创建和读取数据库。我可以使用 find() 从集合中读取数据,但不能使用 find() 函数中的数据。当我尝试在函数外部使用数据时,它显示未定义。有人可以帮助我并分享我如何从 find() 函数中导出数据。
var importantData;
Important.find(function(err,data){
if(err){
console.log(err)
} else {
importantData = data;
}
})
console.log(importantData)
【问题讨论】:
标签:
node.js
mongodb
mongoose
crud
【解决方案1】:
有两种方法可以保存.find() 查询结果以供以后使用。第一个是使用 .then(),第二个是使用 async/await。不管怎样,别忘了添加错误处理!
使用 .then()
let importantData
Important.find({})
.then((data) => {
console.log("Important Data found! ", data)
importantData = data
// now data is accessible from outside the then block
})
.catch((err) => {
console.log(err)
})
使用异步/等待
// Don't forget the try/catch block if you use Async/Await!
try {
const importantData = await Important.find({})
console.log("Important Data found! ", importantData)
} catch (exception) {
console.log(exception)
}