我正在尝试返回 Mongoose 文档的字段值。我有一个菜谱模式,在其中,我概述了一个名为“postedBy”的值,它基本上是提交菜谱的人的 _id。这是配方模型的代码:
let recipeSchema = new Schema({
// I have other values in the schema, but for clarity sake,
// I clearly have the field value defined in the schema model.
postedBy: {
type: String,
required: true,
index: true
}
});
现在这是我遇到问题的代码:
/// Here I make my function that returns the postedBy field value in
///question
let getRecipeMaker = (recipeId) => {
return Recipe
.findOne({_id: recipeId})
.then((recipe) => {
/// So far this is good, this console.log is printing out
/// the field value I want
console.log('What is being returned is ' + recipe.postedBy);
return recipe.postedBy;
})
.catch((err) => {
console.log(err)
});
};
// Then here, I am setting the returned result of the function to a
// variable. My req.params.recipeId is already outlined
// in the router this code is in, so that's not the issue.
let value_ = getRecipeMaker(req.params.recipeId)
.then((chef) => {
// This console.log is printing the value that I want to the
// console. So I should get it.
console.log('chef is ' + chef);
});
/// But whenever I am console.logging the variable, I keep getting
///[object Promise] instead of the value I want
console.log('value_ is ' + value_);
谁能帮帮我。
最佳答案
这是您使用 Promise 的方式存在的问题。您的最终控制台日志位于 promise 链之外。您的最终 console.log 实际上在数据库有机会查询结果之前执行。如果您希望范围超出 promise ,您可以在拿到食谱制作器后返回厨师
let value_ = getRecipeMaker(req.params.recipeId)
.then((chef) => {
// This console.log is printing the value that I want to the
// console. So I should get it.
console.log('chef is ' + chef);
return chef;
});
那么你的最终控制台日志在哪里
value_.then(chef => {
console.log(chef);
});
关于javascript - 我想从 MongoDB 文档返回特定字段值,但我不断将 [object Promise] 作为返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44573775/