簡體   English   中英

如何從 mongoose 查詢返回一個變量,它返回 Promise {< pending >}

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM