2016-06-26 129 views
0
router.route('/') 
    .post((req, res) => { 
     Circle.findOne({title: req.params.circle_title}, (err, circle) => { 
     if (err) { 
      return res.send(err) 
     } 

     circle.posts.push({ 
      authorId: req.body.authorId, 
      body: req.body.body 
     }) 

     circle.save((err, savedCircle) => { 
      if (err) { 
      return res.send(err) 
      } 

      res.json(savedCircle.posts[savedCircle.posts.length-1]) // FIXME 
     }) 
     }) 
    }) 

在上面的代碼中的子文檔,我想知道是否有更好的方法來返回剛保存的,這是一個circle的子文檔post貓鼬讓剛剛存

+0

爲什麼不返回'_id'新職位和查詢'郵政'收集? – Baruch

+0

如果答案不符合標準/不適用於您,您是否可以更新評論中的原因? –

回答

0

您可以嘗試以下操作:

你後,立即保存,你需要findOne和填充:

circle.save((err, savedCircle) { 

     if (err) { 
     return res.send(err) 
     } 

     Circle.findOne(savedCircle).populate('post.Ref_Id').exec(function(err, results) { 
      console.log(results); 
     }); 

     res.json(results); 

    }) 
} 


即使你可以對所得/保存的文檔直接做。

savedCircle.populate('post.Ref_Id').exec(function(err, results) { 
    console.log(results); 
}); 


最好的辦法是擁有最近被推對象的引用。例如:

circle.posts.push({ 
     authorId: req.body.authorId, 
     body: req.body.body 
    }); 
    latestSavedcirclePost = circle.posts[0]; //Here you will get _id ref as well 


你可以嘗試使用推的創建方法,而不是/將它們添加到陣列中,如:

var latestSavedcirclePost = circle.post.create({ 
     authorId: req.body.authorId, 
     body: req.body.body 
});