猫鼬中的 findOne 返回空对象,然后返回正确的对象

时间:2021-06-18 08:57:31

标签: javascript mongodb asynchronous web mongoose

我正在尝试将现有配方从我的数据库添加到用户,这是我的功能:

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;
    }
  });
  }

当我这样调用这个函数时:

model.addRecipeToUser("a@b.com","pancake");

这是我得到的:

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
}

在robo 3T中,保存的值为Null, 我在没有异步的情况下尝试过,但得到了相同的结果,我查看了其他问题并尝试了答案,但仍然未定义。 为什么 findRecipe 在 console.log 之后被调用? 我该怎么做才能得到正确的对象?

2 个答案:

答案 0 :(得分:2)

您将回调与 async/await 混合使用,并且未正确使用 async/await。

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)
 }
}

答案 1 :(得分:1)

我真的想通了,我希望这会帮助某人:

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);
  });

}