【发布时间】: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