如何 return 来自 mongoose 查询的变量,它 returns Promise {< pending >}
How to return a variable from a mongoose query, it returns Promise {< pending >}
我正在构建一个使用 mongo 数据库的后端程序,但我不能 return 在 mongoose 查询的代码中使用变量. async managemenet肯定有问题。
我已经用非常简单的代码总结了我想做的事情:我必须从 ID 中找到名称并使用它。
假设有一些架构 Thing 类型:
const ThingSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String
}
在 url 的路由器中,我收到了一个获取请求:
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": {} }
我不傻,我已经搜索了几十个主题和官方指南,并进行了各种尝试,但我不知道怎么做。
(抱歉英语不好,我来自意大利)
你的方法returns一个承诺,所以你需要像这样等待它。
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() 将 return 一个承诺。在您的路由处理程序中使用此承诺。
将您的路由处理程序更改为:
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);
})
})
或者使用 async await 作为:
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();
}
我正在构建一个使用 mongo 数据库的后端程序,但我不能 return 在 mongoose 查询的代码中使用变量. async managemenet肯定有问题。
我已经用非常简单的代码总结了我想做的事情:我必须从 ID 中找到名称并使用它。
假设有一些架构 Thing 类型:
const ThingSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String
}
在 url 的路由器中,我收到了一个获取请求:
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": {} }
我不傻,我已经搜索了几十个主题和官方指南,并进行了各种尝试,但我不知道怎么做。
(抱歉英语不好,我来自意大利)
你的方法returns一个承诺,所以你需要像这样等待它。
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() 将 return 一个承诺。在您的路由处理程序中使用此承诺。
将您的路由处理程序更改为:
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);
})
})
或者使用 async await 作为:
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();
}