Relationships:
- A
one-to-one is a relationship
such that a state has only one
capital city and a capital city is the capital of only one state
- A
one-to-many is a relationship
such that a mother has many
children, and the children have only one mother
- A
many-to-many is a relationship
such that a book can be written by
several authors or co-authors, while an author can write several
books.
one-one relationship - If a Project/Group
is removed, how can i update my Assignment
Schema.
Typically you will have one project
mapped to one assignment
and similarly one assignment
mapped to one project
. what you can do here is removing a project and then find the associated project
in assignment model and remove their references.
delete: function(req, res) {
return Project.findById(req.params.id, function(err, project){
return project.remove(function(err){
if(!err) {
Assignment.update({_id: project.assignment}},
{$pull: {projects: project._id}},
function (err, numberAffected) {
console.log(numberAffected);
} else {
console.log(err);
}
});
});
});
}
one-many relationship - If a Project/Group
is removed, how can i update my Assignment
Schema.
In this scenario we are removing a project and then finding all the assignments
which belongs to this project
and removing its reference from them. Here the situation is, there can be many assignments for a single project.
delete: function(req, res) {
return Project.findById(req.params.id, function(err, project){
return project.remove(function(err){
if(!err) {
Assignment.update({_id: {$in: project.assingments}},
{$pull: {project: project._id}},
function (err, numberAffected) {
console.log(numberAffected);
} else {
console.log(err);
}
});
});
});
}
Remove middleware
You could achieve the same thing via middleware
as pointed out by Johnny, just a correction on that..
ProjectSchema.pre('remove', function (next) {
var project = this;
project.model('Assignment').update(
{ projects: {$in: project.assignments}},
{ $pull: { project: project._id } },
{ multi: true },
next
);
});
Typically there can be many projects
belonging to an assignment
and many assignments
belonging to the same project
. You will have an assignment
column in your Project
Schema where one project will relate to multiple assignments.
Note: remove middleware won't work on models and it would only work on your documents. If you are going with remove
middleware ensure in your delete function, you find project
by id first and then on the returned document
apply the remove method, so for the above to work... your delete function would look like this.
delete: function(req, res) {
return Project.findById(req.params.id, function(err, project){
return project.remove(function(err){
if(!err) {
console.log(numberAffected);
}
});
});
}