2016-06-26 208 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 
});