Reputation: 33
I am trying to add an existing recipe to a user from my database, here are my functions:
exports.addRecipeToUser = (user,recipeName) => {
let recipe = this.findRecipe(recipeName);
console.log("i am in model",recipe)
User.updateOne({username: user},{ $push: { recipes: recipe} },function (err) {
if (err) console.log(err);
});
}
exports.findRecipe = async (recipeName) => {
Recipe.findOne({name: recipeName}, function (err, docs) {
if (err){
return err;
}
else{
console.log("testing 1111111111",docs);
return docs;
}
});
}
when I call this function like this :
model.addRecipeToUser("[email protected]","pancake");
this is what I get:
i am in model Promise { undefined }
testing 1111111111 {
categories: [ 'Dessert' ],
_id: 60cb54b80790970dab918bbc,
name: 'pancake',
img: 'https://www.auxdelicesdupalais.net/wp-content/uploads/2020/06/pancakes-fluffy-2.jpg',
description: 'e2e2e2 dewf; ewk kks lel f ',
ingredients: [
{
_id: 60cb54bc0790970dab918bbe,
name: 'cheese',
quantity: 2,
unit: ''
}
],
steps: [
{
_id: 60cb54bf0790970dab918bc0,
description: 'e2e2e2 dewf; ewk kks lel f ',
img: 'https://www.auxdelicesdupalais.net/wp-content/uploads/2020/06/pancakes-fluffy-2.jpg'
}
],
__v: 0
}
In robo 3T, the value that is saved is Null, I tried without the async and I get the same result, I looked at other questions and tried the answers and it is still undefined. why is findRecipe Called after the console.log? what can I do to get the correct object?
Upvotes: 1
Views: 331
Reputation: 1785
You are mixing callbacks with async/await, and using async/await not properly.
exports.addRecipeToUser = async (user,recipeName) => {
try {
const recipe = await Recipe.findOne({name: recipeName});
await User.updateOne({username: user}, { $push: { recipes:
recipe} });
} catch(error) {
console.error(error)
}
}
Upvotes: 2
Reputation: 33
I actually figured it out, I hope this will help someone:
exports.addRecipeToUser = async (user,recipeName) => {
let recipe = await Recipe.findOne({name: recipeName}, function (err, docs) {
if (err){
return err;
}
else{
console.log("testing 1111111111",docs);
return docs;
}
});
console.log("i am in model",recipe)
User.updateOne({username: user},{ $push: { recipes: recipe} },function (err) {
if (err) console.log(err);
});
}
Upvotes: 1