2017-02-03 6 views
0

私はmongodbが新しく、フィールドユーザー(IDで参照)に投稿を返し、更新された投稿を返す新しいコメントを挿入しようとしています。 populateオプションを使用して1つのクエリだけを返しますか?ここで私のコードは動作していますが、その種類は遅いです。なぜなら、2つの '検索'クエリがあるからです。 1つのデータを取り込むだけでそれを行う別の方法はありますか?Mongodbは、更新されたオブジェクトをポピュレートで返す

 var newComment = { 

      comment:req.body.text, 
      isEdit:false, 
      user:req.body.user 

     }; 

     comments.create(newComment,function(err,commentCreated){ 

      post.find({_id:req.params.postId},function(err,postFound){ 

       if(err){ 
        throw err; 
       } 
       else{ 

        postFound[0].comments.push(commentCreated); 
        post[0].save(function(){ 
         post.find({_id:req.params.videoId}).populate({path:'comments',populate:{path:"user",model:"users"}}) 
         .exec(function(err,data){ 

         if(err){ 
          throw err; 
         } 
         else{ 
          res.json(data); 

         } 
       }) 

      }); 









      }) 

答えて

0

使用あなたが移入できQuery返しfindByAndUpdate()Mongoose Promiseを返すように関数にexec()を呼び出し、これあなたが

var postId = req.params.postId; 
var newComment = new Comment({ 
    comment: req.body.text, 
    isEdit: false, 
    user: req.body.user 
}); 

newComment.save().then(function(comment){ 
    Post.findByIdAndUpdate(
     postId, 
     { "$push": { "comments": comment._id } }, 
     { "new": true, "upsert": true } 
    ) 
    .populate({ 
     "path": "comments", 
     "populate": { 
      "path": "user", 
      "model": "users" 
     } 
    }) 
    .exec(); 
}) 
.then(function(data) { res.json(data); }) 
.catch(function(err) { throw err; }); 
+0

に、現在のコードを変換することができますありがとうございました!完全に動作します –

+0

実際に私は.exec(関数(err、data){res.json(data});最後に.thenを使う代わりに、その作業も。 –

関連する問題