这是我正在尝试做的一个示例,检索 mongo db 中的所有帖子,为每个帖子填充作者,然后使用作者对象从 Cloudinary 检索个人资料图片。
这样做的正确方法是什么?我尝试了多种填充数组并在响应中发送它们的方法,但是由于异步调用,它们在发送 res 之前永远不会运行。
router.get('/posts',auth, function(req, res, next) {
//var id = req.payload._id;
Post.find(function(err, posts){
if(err){ return next(err); }
posts.forEach(function(post){
post.populate('author',function(err,post){
post.image = cloudinary.image("v"+post.author.avatarVersion+"/profile/"+post.author._id,{
width:100, height:100,crop:'thumb',gravity:'face',radius:'max'
})
//here the post object is updated
console.log(post)
})
})
//res.json(some posts array);
});
});
感谢 Dan Moldovan 的解决方案!
router.get('/posts',auth, function(req, res, next) {
var id = req.payload._id;
Post.find({}).populate('author').exec(function(err,posts){
if(err){ return next(err); }
var updatedPosts = [];
posts.forEach(function(post){
post.image = cloudinary.image("v"+post.author.avatarVersion+"/profile/"+post.author._id,{
width:100, height:100,crop:'thumb',gravity:'face',radius:'max'
})
updatedPosts.push(post);
})
res.json(updatedPosts);
})