这是我的架构:
var userschema = new mongoose.Schema({
user: String,
imagen: [{
name: String,
author: String,
date: { type: Date, default: Date.now },
}],
follow: [String]
});代码是这样的:
usermodel.findOne({ user: req.session.user }, function (err, user){
usermodel.find({ _id: {$in: user.follow } }, function (err, images){
console.log(images);
if (err) throw err;
res.render('home.ejs', {
user: user,
following: images
});
});
});架构中的以下数组包含实际用户所关注的用户的_id。我正在尝试获得如下输出:
{ _id: 50fd9c7b8e6a9d087d000006,
imagen:
[ { name: 'fff.png',
author: 'foo',
_id: 50fd9ca2bc9f163e7d000006,
date: Mon Jan 21 2013 20:53:06 GMT+0100 (CET) },
{ name: 'mmm.png',
author: 'foo',
_id: 50fda83a3214babc88000005,
date: Mon Jan 21 2013 21:41:34 GMT+0100 (CET) } ] },
{ _id: 50fd9d3ce20da1dd7d000006,
imagen:
[ { name: 'ddd.jpg',
author: 'faa',
_id: 50fda815915e068387000005,
date: Mon Jan 21 2013 21:42:57 GMT+0100 (CET) } ] }我试着在下面得到类似的输出,例如:
{ [ { name: 'fff.png',
author: 'foo',
_id: 50fd9ca2bc9f163e7d000006,
date: Mon Jan 21 2013 20:53:06 GMT+0100 (CET) },
{ name: 'ddd.png',
author: 'faa',
_id: 50fda815915e068387000005,
date: Mon Jan 21 2013 21:42:34 GMT+0100 (CET) },
{ name: 'mmm.png',
author: 'foo',
_id: 50fda83a3214babc88000005,
date: Mon Jan 21 2013 21:41:34 GMT+0100 (CET) }
] }我认为我想要的是不可能的,或者非常复杂的,有什么解决方案吗…?
谢谢你的预支!
发布于 2013-01-26 04:28:51
在这一行中:
usermodel.find({ _id: {$in: user.follow } }, function (err, images){images不是一个好名字,更好的名字是users,甚至是docs (在那里您会有一组usermodel模式的文档)。因此,代码中的images都是可找到的文档。
我已经使用与您给出的相同的模式进行了一个小测试。下面是我连接所有user.imagen数组,然后对它们进行排序的部分(当然这是测试用例,但它是有效的,希望这将引导您找到正确的方法):
User.find {}, (err, users) ->
all_images = []
# iterate users array to join all imagen arrays
for user in users
all_images.push user.imagen
# flatten nested arrays in all_images with underscore function
all_images = _.flatten all_images
# sort all_images the way you want (i.e. descending)
all_images.sort (a, b) -> b.date - a.date
# render page and see that it works
res.render 'test.html', {images: all_images}https://stackoverflow.com/questions/14447871
复制相似问题