LearnBoost/mongoose — Issue #710: recursive populate
Author: unit51
Created: 2012-02-02 08:25:27+00:00
State: open

Hello,

i have this Schema:

```javascript
var ChatSchema = new Schema({
title: String,
founderUser : { type: Schema.ObjectId, ref: 'User'},
members : [{ type: Schema.ObjectId, ref: 'User'}],
messages : [{ type: Schema.ObjectId, ref: 'Message'}],
});

var MessageSchema = new Schema({
sender: { type: Schema.ObjectId, ref: 'User' },
date: { type: Date, default: Date.now },
text: String,
});
```

now i want to query a chat:

```javascript
Chat
.findOne({ _id:obj._id})
.populate('founderUser', ['username', '_id'])
.populate('members', ['username', '_id'])
.populate('messages', ['_id'], null, { limit: 10, sort: [['date', 'asc' ]] })
```
but i also want to populate the messages sender (username & _id)
Something like this:

```javascript
.populate('members.sender', ['username', '_id'])
```
would be very helpful.

This is my current solution (kinda ugly o_o )

```javascript
Chat
.findOne({ _id: item.obj._id})
.populate('founderUser', ['username', '_id'])
.populate('members', ['username', '_id'])
.populate('messages', ['_id'], null, { limit: 10, sort: [['date', 'asc' ]] })
.run(function (err, chat) {
Message
.find({ _id: { $in : chat.messages } })
.populate('sender', ['username', '_id'])
.run(function (err, messages) {
var jsonObject = chat.toObject();
jsonObject.messages = messages;

callback(jsonObject);
})

});
```
i cant use embedded documents for the messages because i cannot filter the messages { limit: 10, sort: [['date', 'asc' ]] }