[英]Mongoose findOne() in several collections
I'm building a deletion process where I need to find out if a certain document is referenced from another documents before deleting the original document. 我正在建立一个删除过程,在删除原始文档之前,我需要确定是否从其他文档中引用了某个文档。
In the example below, I need to find out if a given Company is used somewhere in my other documents: 在下面的示例中,我需要确定我的其他文档中是否使用了给定的公司:
Model metadata: 模型元数据:
Company = {
id: ID,
name: name
}
User = {
id: ID,
name: name,
company_id: ID
}
Application = {
id: ID,
type: string,
company_id: ID
}
...
Here is what I would do using asynchronous calls: 这是我将使用异步调用执行的操作:
const checkInUse = async (company_id) => {
let ret = await UserModel.findOne({ company_id: company_id });
if (ret) return true;
ret = await ApplicationModel.findOne({ company_id: company_id });
if (ret) return true;
...
return false;
}
I have some dozen of collections, so some checks would take several calls to findOne()
, and that's what I want to avoid. 我有几十个集合,因此一些检查将需要多次调用findOne()
,这就是我要避免的事情。
Is there is a better way of doing this check ? 有没有更好的方法来执行此检查?
Yes, use only find()
instead of findOne()
and the filters you want to specify, it will return a Mongoose list of documents. 是的,仅使用find()
而不是findOne()
和要指定的过滤器,它将返回一个Mongoose文档列表。
Source: http://mongoosejs.com/docs/queries.html 资料来源: http : //mongoosejs.com/docs/queries.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.