Я хочу вернуть определенное значение поля из документа MongoDB, но вместо этого получаю [обещание объекта] в качестве возвращаемого значения

1

Я пытаюсь вернуть значение поля для документа в мангусте. У меня есть схема рецепта, и в нем я изложил значение, называемое "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_);

Может кто-нибудь мне помочь.

Теги:
mongoose
mongodb-query

1 ответ

1
Лучший ответ

Это проблема в том, как вы работаете с обещаниями. Конечный консольный журнал находится вне цепочки обещаний. Ваш последний 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);
});
  • 0
    Если я хочу использовать переменную value_ для других целей, должен ли я поместить код в это обещание value_.then () или я могу использовать его вне его?
  • 0
    Вы должны поместить код внутри функции then. Обычно все программирование на основе обещаний будет выглядеть так. Я бы рекомендовал изучить стили кодирования обещаний немного больше.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню