This is my Schema:
var userschema = new mongoose.Schema({
user: String,
imagen: [{
name: String,
author: String,
date: { type: Date, default: Date.now },
}],
follow: [String]
});
And this is the code:
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
});
});
});
The follow array in the Schema contains the _id
s of the users that the actual user is following. I'm trying to get an output like this:
{ _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) } ] }
And I'm trying to get an output similar at this, for example:
{ [ { 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) }
] }
I think that what I want is imposible, or very complex, is there any solution for this...?
Thank's advance!
In this line:
usermodel.find({ _id: {$in: user.follow } }, function (err, images){
images
is not good name, nicer name is users
or even docs
(you'll have an array of documents of usermodel schema there). So images
in your code are found documents.
I've made a little test with the same schema as you gave. Here is the part where I join all user.imagen
arrays and then sort them (of course it is test case but it works, hope this will lead you to the right way):
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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.