0

I'm trying to use the mongoose to try to fetch all the records under the Profile Schema using the find() method. The code looks fine to me and when I console.log the code block, it returns Promise { <pending> }.

I tried different approaches with no hope. Any help would be appreciated. Thanks,

Here is my Code:

return Profile.find()
    .then(profiles => {
        return profiles.map(profile =>{
            return {
            ...profile._doc
            };
        });
    }).catch(err => {
        //console.log(err);
        throw err;
    })
Pingolin
  • 3,161
  • 6
  • 25
  • 40
  • 1
    where did you put `console.log`? – alt255 Feb 05 '19 at 08:06
  • 2
    That's what a promise is. If you need its value you need to await it (with a `then` callback). You can never expect it to be available synchronously. That would be like drinking the beer that you just asked your friend to go get from the fridge. – trincot Feb 05 '19 at 08:06
  • https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – str Feb 05 '19 at 08:10
  • @alt255 around the code block Instead of returning it. I'm using this code for building a graphql API. Thanks, – Matthew George Feb 05 '19 at 08:14

1 Answers1

0

That would be because the promise is in pending state.If you need the data after the promise has been resolved you would have to add a then callback.

function getProfiles(){
   return Profile.find()
       .then(profiles => {
          return profiles.map(profile =>{
             return {
                ...profile._doc
             };
          });
       }).catch(err => {
          //console.log(err);
          throw err;
       })
}

getProfiles().then(profiles => console.log('profiles',profiles))
anuragb26
  • 1,467
  • 11
  • 14
  • I'm still getting a Promise {} output while running this code. Can you Help me out ? console.log( getProfiles().then(profiles => { //console.log('profiles',profiles) return { ...profiles._doc, } })); – Matthew George Feb 05 '19 at 08:29
  • Basically I want to return an object from the function. – Matthew George Feb 05 '19 at 08:30
  • The returned object from getProfiles() is what you should be getting in getProfiles().then callback. Can you show more of the code where you are getting the object. – anuragb26 Feb 05 '19 at 08:35
  • profiles: () => {getProfiles().then(profiles => { //console.log(profiles); return profiles; }); }, – Matthew George Feb 05 '19 at 08:42
  • You are again returning a promise from the profiles method.As long as you do that, you need to have .then handler to get the data. and write code using that data in the .then handler.Otherwise you will get the pending promise. – anuragb26 Feb 05 '19 at 09:31