[英]How to return a variable from a mongoose query, it returns Promise {< pending >}
我正在构建一个与 mongo db 一起使用的后端程序,但我无法从 mongoose 查询返回要在代码中使用的变量。 异步管理网肯定有问题。
我已经用非常简单的代码总结了我想要做的事情:我必须从 ID 中找到名称并使用它。
想象一下,有一些Thing类型的模式:
const ThingSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String
}
在路由器的 url 中,我有一个 get 请求:
router.get('/:id', (req, res, next) => {
const id = req.params.id;
const name = findName(id);
console.log(name);
res.status(200).json({name: name});
});
所以我创建了查找名称的函数
function findName(id){
var name = Thing.findById(id)
.exec()
.then(docs =>{
var string = "the name is: " + docs.name;
return string
});
return name
}
当我发送带有有效 ID 的 GET 请求时,它给了我:
在日志中:Promise { }
obv 回应:{ "name": {} }
我不傻,我已经搜索了几十个主题和官方指南并进行了各种尝试,但我不明白如何做到。
(抱歉英语不好,我是意大利人)
您的方法返回一个承诺,因此您需要像这样等待它。
router.get('/:id', async(req, res, next) => {
const id = req.params.id;
const name = await findName(id);
console.log(name);
res.status(200).json({name: name});
});
您的exec()将返回一个承诺。 在您的路由处理程序中使用此承诺。
将您的路由处理程序更改为:
router.get('/:id', (req, res, next) => {
const id = req.params.id;
findName(id)
.then((res)=>{
res.status(200).json({name: name});
})
.catch((err)=>{
res.status(500).send(err);
})
})
或者使用异步等待作为:
router.get('/:id', async(req, res, next) => {
try{
const id = req.params.id;
const name= await findName(id);
res.status(200).json({name: name});
}
catch(err){
res.status(500).send(err);
}
})
将您的 findName 函数更改为:
function findName(id){
return Thing.findById(id).exec();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.