node js mongoose delete a from an id in document array

Viewed 10774

I've two collection of reference both collection together. One of the collection is user and the other collection is project.

So, a user can add project to the projects collection, then one of the user type called supervisor can add staff to the project and the project id saved to the user collection which referred to staff document on the project collection.

So actually i need to do when admin deletes a supervisor from the user collection it deletes all the projects created by supervisor users's id that equal to addedBy documents which deleted from the users collection.

So my problems is when i do this process i need to delete all the project id is equal to the users collection projectId. it's an array and I tried to do this to many times but i couldn't find a solution. I'll provide all of the source code. That i created for this project.

Users collection

const userSchema = new Schema({


firstName: {
        type: String
    },
    lastName: {
        type: String
    },
    email: {
        type: String
    },
    username: {
        type: String
    },
    password: {
        type: String
    },
    usertype: {
        type: Schema.ObjectId,
        ref: 'usertypes'
    },
    projectId: [{
        type: Schema.ObjectId,
        ref: 'projects'
    }]
});

Project collection

const proSchema = new Schema({
projectName: {


    type: String
    },
    description: {
        type: String
    },
    addedBy: {
        type: Schema.ObjectId,
        ref: 'users'
    },
    staff: [{
        type: Schema.ObjectId,
        ref: 'users'
    }]
});

Here is the query that i tried to do the process that i mentioned in above

Users
.findByIdAndRemove({
    _id: req.params.id
})
.then(function(){
    Projects
    .remove({
        userId: req.params.id
    })
    .then(function(err, project){
        if(err) throw err;
        console.log(project.id)
        Users
        .update({}, { 
            $pull: {
                projectId: project.id
            }
        }, function(){
            res.json({
                success: true,
                message: "Deleted"
            });
        });
    });
});
2 Answers
User.findByIdAndUpdate(req.params.idRec, 
{ $pull: { comments: { _id: comm._id } } }, 
 function (err, doc) {
                    if (!err) {
                        res.status(200).send()
                    } else {
                        res.render('error', { error: err })
                    }
                })
Related