mongooseでドキュメントのフィールド値を返そうとしている。私はレシピスキーマを持っており、その中には、基本的にレシピを提出した人のIDである "postedBy"と呼ばれる値がありました。ここでレシピモデルのコードは次のとおりです。MongoDBドキュメントから特定のフィールド値を返したいが、代わりに[オブジェクトPromise]を返り値として返す
/// 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_);
誰も私を助けることができる:
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
}
});
今ここで、私は問題を抱えていたコードです。
あなたは既に解決策を知っているように見えるです'then'コールバックの値を使用するコードですか? – Bergi