Mongoose returns undefined even with await. Any guess of may be wrong?

Viewed 210

I am testing some functionalities in mongoose, I want o learn new things. I am playing with subdocuments. Consider the code below. Why is doc printed as undefined? I am using await, it should wait, shouldn’t it?

pushSubdocument();//calls the function

async function pushSubdocument() {
  const doc = await findByIdMongoose(); //I ask to await
  console.log(doc);//I am printing here, and it is undefined
}
function findByIdMongoose() {
  Document.findById({ _id: "5e6d0f3e8afae22ee0cc238c" })
    .select("friends")
    .then(doc => {
        doc.friends.push({
        name: "Maria",
        email: "mariadomar@test.com",
        relatives: []
      });

      doc.save().then(() => {
        console.log("saved!");
      });
// if I print it here, before returning, it is okay
      return doc;
    });
}

Related question: Async Await with Mongoose Returns Empty Object

1 Answers

The findByIdMongoose() will return undefined because ,the doc you are trying to return from it will get returned after this function gets called asynchronous nature of node js. And there is no reason to await non async function findByIdMongoose().

You can do something like this

async function pushSubdocument() {
  const doc = await findByIdMongoose(); //I ask to await
  console.log(doc);//I am printing here, and it is undefined
}
async function findByIdMongoose() {

let doc= await Document.findById({ _id: "5e6d0f3e8afae22ee0cc238c" }).select("friends");

 doc.friends.push({
        name: "Maria",
        email: "mariadomar@test.com",
        relatives: []
      });
await doc.save();
return doc ; // now it will be wrapped in promise and you can await the function


}
Related