문제

I have the following schemas:

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'}
});

I now want to query the database for a specific sprint, with all tasks fully populated. By that I mean that the sprint object should not only contains the populated tasks, but the assignee (and project) for each task should be populated as well.

My code is now the following:

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);
});

But the assignee is still not populated! What am I doing wrong?

도움이 되었습니까?

해결책

Fixed this using extra populate commands:

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
        });
    });     
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top