【问题标题】:findOne in mongoose returns empty object and then the correct one猫鼬中的 findOne 返回空对象,然后返回正确的对象
【发布时间】:2021-09-03 00:27:53
【问题描述】:

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

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, 我尝试不使用异步并且得到相同的结果,我查看了其他问题并尝试了答案,但它仍然未定义。 为什么在console.log之后调用findRecipe? 我该怎么做才能得到正确的对象?

【问题讨论】:

    标签: javascript mongodb asynchronous web mongoose


    【解决方案1】:

    您将回调与 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)
     }
    }

    【讨论】:

    • 我不应该添加回调以防出错吗?谢谢你的回答顺便说一句
    • 不,你将 try/catch 与 async/await 一起使用,并将 .catch 与 Promises 一起使用
    • 更新了答案。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 2018-08-07
      • 1970-01-01
      • 2018-04-03
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-06
      相关资源
      最近更新 更多