Я пытаюсь вернуть значение поля для документа в мангусте. У меня есть схема рецепта, и в нем я изложил значение, называемое "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 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_);
Может кто-нибудь мне помочь.
Это проблема в том, как вы работаете с обещаниями. Конечный консольный журнал находится вне цепочки обещаний. Ваш последний console.log фактически выполняется до того, как база данных сможет запросить результаты. Если вы хотите, чтобы сфера была вне обещания, вы можете вернуть шеф-повара после того, как получите рецепта
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);
});