javascript - 我想从 MongoDB 文档返回特定字段值,但我不断将 [object Promise] 作为返回值

标签 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_);

谁能帮帮我。

最佳答案

这是您使用 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/

相关文章:

javascript - Mongodb $push 对象首先将其包装在数组中

arrays - 在 mongoDB 中索引大数组

javascript - 使用 JSON.parse() 检索本地存储数组列表

javascript - 帧中的动画持续时间是什么意思?

javascript - 当输入宽度在 Safari 中变小时,表单不会缩小

javascript - 如何在nodejs中将一个api请求转换为另一个api请求

node.js - 如何在使用集群模块的 Node.js 应用程序中运行 Cron Job?

javascript - 我们如何从 1 :Array(10) 获取数据

node.js - Travis-CI 找不到相关模块要求

node.js - 使用 collectionfs 更新图像