无法在填充数组中填充引用

时间:2014-01-02 10:07:47

标签: mongodb mongoose populate

我有以下架构:

var SprintSchema = new Schema({
    name: {type: String},
    startDate: Date,
    endDate: Date,
    tasks: [{type: Schema.ObjectId, ref: 'Task'}]
});
var TaskSchema = new Schema({
    title: String,
    project: {type: Schema.ObjectId, ref: 'Project'},
    bp: Number,
    status: {type: Number, default: 0},
    description: String,
    assignee: {type: Schema.ObjectId, ref: 'User'},
    comments: [{
        author: {type: Schema.ObjectId, ref: 'User'},
        comment: String,
        systemMessage: String,
        time : { type : Date, default: Date.now}
    }],
    sDate: Date
});
var UserSchema = new Schema({
    googleId: {type: String, default: ''},
    firstName: {type: String, default: ''},
    lastName: {type: String, default: ''},
    email: {type: String, default: ''},
    profilePicture: {type: String, default: '/images/user.png'},
    accessToken: {type: String, default: ''},
    role: {type: String, default: 'employee'}
});

我现在想要查询数据库中的特定sprint,所有任务都已完全填充。我的意思是sprint对象不仅应包含填充的任务,还应填充每个任务的受理人(和项目)。

我的代码现在如下:

Sprint.findById(req.params.id).populate('tasks').populate('tasks.assignee').exec(function(err, sprint) {
        if(err) {
            console.log('SprintView:: error while fetching the sprint: ' + err);
            res.statusCode = 400;
            res.send('NOT OK');
            return;
        }
        for(var i = 0; i < sprint.tasks.length; i++) {
            console.log(sprint.tasks[i]);
        }
        console.log(sprint);
});

但受让人仍未填充!我做错了什么?

1 个答案:

答案 0 :(得分:1)

使用额外的填充命令解决了这个问题:

Sprint.findById(req.params.id).populate('tasks').exec(function(err, sprint) {
    User.populate(sprint, {path: 'tasks.assignee'}, function(err, sprint) {
        Project.populate(sprint, {path: 'tasks.project'}, function(err, sprint) {
            //Do something cool here
        });
    });     
});