【问题标题】:How to return a variable from a mongoose query, it returns Promise {< pending >}如何从 mongoose 查询返回变量,它返回 Promise {< pending >}
【发布时间】:2020-05-20 16:47:00
【问题描述】:

我正在构建一个与 mongo 数据库一起工作的后端程序,但我无法从 mongoose 查询返回要在代码中使用的变量。异步管理网一定有问题。

我已经用非常简单的代码总结了我想要做的事情:我必须从 ID 中找到名称并使用它。

想象有一些 Thing 类型的架构:

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

在路由器中我有一个获取请求:

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": {} }

我不傻,我已经搜索了几十个主题和官方指南,做了各种尝试,但我不知道怎么做。

(抱歉英语不好,我来自意大利)

【问题讨论】:

    标签: node.js asynchronous mongoose promise return-value


    【解决方案1】:

    您的方法返回一个承诺,因此您需要像这样等待它。

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

    【讨论】:

    • 成功了,非常感谢!从指南中不太容易理解您必须在哪里使用 async/await,我在“findName”中使用过,但它不起作用,再次感谢!
    【解决方案2】:

    您的 exec() 将返回一个承诺。在你的路由处理程序中使用这个 Promise。

    将您的路由处理程序更改为:

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

    【讨论】:

    • 它有效,我已经知道第一个方法,但我想调用辅助函数,关键是在路由处理程序中使用 asyncawait 函数前,非常感谢!
    猜你喜欢
    • 2018-08-19
    • 2023-04-01
    • 2021-04-21
    • 1970-01-01
    • 2013-11-22
    • 2019-12-23
    • 2020-07-09
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多