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