[英]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.在 robo 3T 中,保存的值为 Null,我尝试不使用 async 并得到相同的结果,我查看了其他问题并尝试了答案,但仍然未定义。 why is findRecipe Called after the console.log?
为什么 findRecipe 在 console.log 之后被调用? what can I do to get the correct object?
我该怎么做才能得到正确的对象?
You are mixing callbacks with async/await, and using async/await not properly.您将回调与 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) } }
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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.