有没有一种方法可以将单个Mongoose模式用于多个集合



我为一些实体创建了一个API,每个实体都有自己的模式和相应的集合。例如:

posts
authors
comments

postsauthors之间存在一对一关系,postscomments之间存在一个对多关系。

现在数据大小正在增加,我们计划按客户分配数据,以加快查询和聚合速度。这意味着我们现在将有以下集合:

<customer_1>_posts
<customer_2>_posts
...
<customer_n>_posts
<customer_1>_authors
<customer_2>_authors
...
<customer_n>_authors
<customer_1>_comments
<customer_2>_comments
...
<customer_n>_comments

由于结构在所有<customer_x>_posts中都是公共的,并且在相应的authorscomments中也是类似的,所以我考虑使用公共模式和API。

现在,有没有一种方法可以使用常见的Mongoose模型,并根据客户字段的价值在节省时间时决定数据存储的集合?这将使我不用为每个客户端创建单独的模型,也不用创建单独的端点。

您可以动态构建模型,也可以动态查找和使用模型。

在哪里创建模型:

for (const customer of customerList) {
mongoose.model<CompanyDocument>(`${customer}_comments`, schema)
}

然后使用:

CustomerModel = mongoose.model(`${customer}_comments`)

也就是说,虽然这肯定是可行的,但这不是一个好的模式。如果您正确地使用索引,Mongo应该可以扩展到您的所有用例,而不需要增加复杂性。数以百万计的帖子和评论仍然可以快速、可持续地发布,而无需单独收集。

最新更新