How to restrict delete in MongoDB for relationship

2020-06-28 10:01发布

问题:

Below models we can consider for example:

Companies {Name: string, Address:string}

Employees {FirstName: string, 
           lastName:String, 
           Company: {type:mongoose.schema.objectID,ref:companies}
}

Need to restrict deletion of companies which has employee records at database level, without using "pre" middleware.

I am looking for some solution which is similar to MySQL relationships constraint - on delete restrict.

回答1:

We can do this using $nin

let us have Companies collection with 3 records

db.companies.find();

{"_id":1, "name":"ABC Pvt Ltd", "Address":"Chennai, India"}
{"_id":2, "name":"XYZ Pvt Ltd", "Address":"Mumbai, India"}
{"_id":3, "name":"LMN Pvt Ltd", "Address":"Delhi, India"}

Let us have employees collection with 3 records company attribute in the employees collection refers the document id of companies collection, for testing we have employees for company 1 and 2.

db.employees.find();

{"_id":1, "firstname":"X", "lastname":"Y", "company":1}
{"_id":2, "firstname":"A", "lastname":"B", "company":1}
{"_id":2, "firstname":"Z", "lastname":"A", "company":2}

Before removing the companies without any employees, first we need to find the Companies with employees. To avoid multiple entries let us use distinct

db.employees.distinct("company")
[ 1, 2 ]

now we have used $nin with the distinct companies which has employees to remove the companies which are not having employees

db.companies.remove({"_id":{$nin : db.employees.distinct("company")}});

Now if we execute find query on companies collection we will get only two records.

db.companies.find();
{ "_id" : 1, "name" : "ABC Pvt Ltd", "Address" : "Chennai, India" }
{ "_id" : 2, "name" : "XYZ Pvt Ltd", "Address" : "Mumbai, India" }

company 3 is removed since it has no employees

Hope it Helps!