简体   繁体   中英

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. 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.

Imagine to have some schema for Thing type:

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

And in the router for an url I've got a get request:

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:

In the log: Promise { }

And obv in response: { "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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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