简体   繁体   English

如何从 mongoose 查询返回一个变量,它返回 Promise {< pending >}

[英]How to return a variable from a mongoose query, it returns Promise {< pending >}

I'm bulding a back-end program that work with a mongo db but I can't return a variable to use in the code from a mongoose query.我正在构建一个与 mongo db 一起使用的后端程序,但我无法从 mongoose 查询返回要在代码中使用的变量。 There must be something wrong with async managemenet.异步管理网肯定有问题。

I've summarized what I want to do with very simple code: I've to find the name from an ID and use it.我已经用非常简单的代码总结了我想要做的事情:我必须从 ID 中找到名称并使用它。

Imagine to have some schema for Thing type:想象一下,有一些Thing类型的模式:

const ThingSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String
}

And in the router for an url I've got a get request:在路由器的 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});
});

So I created the function to find the name所以我创建了查找名称的函数

function findName(id){
  var name = Thing.findById(id)
               .exec()
               .then(docs =>{
                  var string = "the name is: " + docs.name;
                  return string
               });
  return name
}

When I send a GET request with a valid id it gives me:当我发送带有有效 ID 的 GET 请求时,它给了我:

In the log: Promise { }在日志中:Promise { }

And obv in response: { "name": {} } obv 回应:{ "name": {} }

I'm not stupid, I've already searched in dozens of topic and official guides and made various attemps but I didn't understood how to made it.我不傻,我已经搜索了几十个主题和官方指南并进行了各种尝试,但我不明白如何做到。

(sorry for bad english, I'm a-from Italy) (抱歉英语不好,我是意大利人)

Your method returns a promise so you need to await it like this.您的方法返回一个承诺,因此您需要像这样等待它。

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

Your exec() will return a promise.您的exec()将返回一个承诺。 Use this promise in your route handler.在您的路由处理程序中使用此承诺。

Change your route handler to:将您的路由处理程序更改为:

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

Or using async await as:或者使用异步等待作为:

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

Change your findName function to:将您的 findName 函数更改为:

function findName(id){ 
return Thing.findById(id).exec();
}

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

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