猫鼬-(MongoDB)中不同集合的相同架构 [英] Mongoose - Same schema for different collections in (MongoDB)
问题描述
我正在创建一个应用程序(Express + MongoDB + Mongoose),在该应用程序中,文档自然按组进行聚类.对数据库的每个查询将只需要访问单个组中的文档.因此,我认为,出于性能考虑,将每个组分成各自的集合是个好主意.
I'm creating an application (Express+MongoDB+Mongoose) where documents are naturally clustered by groups. Every query to the database will only need to access documents from a single group. So I'm thinking it's a good idea to separate each group into its own collection for the sake of performance.
现在,我将对每个集合使用相同的架构,因为它们将存储相同类型的文档.我以前只有一个Model对象,因为过去我把所有东西都放在一个集合中,但是现在我需要多个Model,每组一个.
Now, I'm going to use the same Schema for each of these collections because they will store the same type of documents. I used to have a single Model object because I used to have everything in a single collection but now I need multiple Models, one per group.
在每个请求(使用共享的Schema)上创建一个新的Model对象是一个好主意,还是太昂贵了?在这种情况下,什么是好的架构决策?
Is it a good idea to create a new Model object on every request (using a shared Schema) or is this too expensive? What would be a good architectural decision in this case?
我能想到的最好的方法是,在第一次请求收集时创建模型,然后将模型缓存在字典中以便快速访问.
The best approach I could think of is to create a Model the first time there's a request for a collection and then cache the Models in a dictionary for quick access.
我认为最好的方法取决于在每个请求上创建新的Model对象的成本.
I guess the best approach depends on the cost of creating a new Model object on each request.
谢谢!
推荐答案
Mongoose已经缓存了模型,您可以将同一模式对象用于多个模型/集合.因此,只需使用以下代码(在启动时)创建一次模型集即可:
Models are already cached by Mongoose and you can use the same schema object for multiple models/collections. So just create your set of models once (at startup) using code like:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({...});
var model1 = mongoose.model('model1', schema);
var model2 = mongoose.model('model2', schema);
如果您不想传递model1
,model2
模型实例,则可以通过在处理程序中调用mongoose.model('model1');
来根据需要查找它们.
If you don't want to pass around the model1
, model2
model instances, you can look them up as needed by calling mongoose.model('model1');
in your handlers.
这篇关于猫鼬-(MongoDB)中不同集合的相同架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!