我想从MongoDB文档返回一个特定的字段值,但我继续将[object Promise]作为返回值

时间:2017-06-15 17:45:00

标签: javascript node.js mongodb mongoose mongodb-query

我正在尝试以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_);

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:1)

这是您使用promises的方式中的问题。您的最终控制台日志位于承诺链之外。在数据库有机会查询结果之前,您的最终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);
});