2017-06-15 8 views
1

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 
    } 

}); 

今ここで、私は問題を抱えていたコードです。

+1

あなたは既に解決策を知っているように見えるです'then'コールバックの値を使用するコードですか? – Bergi

答えて

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()の中にコードを置く必要がありますか?それを外してもかまいませんか? – MountainSlayer

+0

あなたはthen関数の中にコードを入れなければなりません。通常、すべての約束ベースのプログラミングはそのように見えます。私は約束のスタイルをもう少し調べることをお勧めします。 – thomasmeadows

関連する問題