本文介绍了如何限制MongoDB中的删除以进行关系收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我们可以考虑以下模型:

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.

我正在寻找一些类似于MySQL关系约束的解决方案-关于删除约束.

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

推荐答案

我们可以使用 $ nin

让我们收集包含3条记录的Companies

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"}

让我们为员工收集3条记录员工集合中的公司属性是指公司集合的文档ID,为了进行测试,我们有公司1和2的员工.

Let us have employees collection with 3 recordscompany 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}

在删除没有员工的公司之前,首先我们需要找到有员工的公司.为了避免出现多个条目,让我们使用 distinct

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 ]

现在我们已将$ nin用于拥有雇员的不同公司,以删除没有雇员的公司

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" }

公司3由于没有员工而被删除

company 3 is removed since it has no employees

希望有帮助!

这篇关于如何限制MongoDB中的删除以进行关系收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:21