mongoose remove from nested documents

Problem

I have the following two schemas and models:

var Customer = new Schema({
    name: String,
    jobs: [{ type: Schema.Types.ObjectId, ref: 'Job' }]
});

var Job = new Schema({
    title: String,
    customer: { type: Schema.Types.ObjectId, ref: 'Customer' }
});

var CustomerModel = mongoose.model('Customer', Customer);
var JobModel = mongoose.model('Job', Job);

job documents have a reference to the customer document via _id, and the customer document also contains an array of all the jobs _id's.

When I delete a job I need to delete the corresponding _id from the Customer.jobs array.

Here is the route I have - the job gets deleted but I cannot remove it's id from the array

app.delete('/api/jobs/:jobId', function(req, res){
    return JobModel.findById(req.params.jobId, function(err, job){
        return job.remove(function(err){
            if(!err){
                CustomerModel.update({_id: job.customer._id}, {$pull : {'customer.jobs' : job.customer._id}}, function(err, numberAffected){
                        console.log(numberAffected);
                        if(!err){
                            return console.log('removed job id');
                        } else {
                            return console.log(err);
                        }
                    });
                console.log('Job removed');
                return res.send('');
            } else{
                console.log(err);
            }
        });
    });
});

numberAffected is always 0 and 'removed job id' always get fired

Problem courtesy of: jamie holliday

Solution

You've got things backwards in your $pull. Try this instead:

CustomerModel.update({_id: job.customer}, {$pull : {jobs : job._id}}, ...
Solution courtesy of: JohnnyHK

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.