vendredi 18 juin 2021

findOne in mongoose returns empty object and then the correct one

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("a@b.com","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?




Aucun commentaire:

Enregistrer un commentaire