Mongoose——不同集合的相同模式(MongoDB)

时间:2021-12-25 18:39:27

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.

我正在创建一个应用程序(Express+MongoDB+Mongoose),在这个应用程序中,文档自然会被分组。对数据库的每个查询只需要访问来自单个组的文档。因此,我认为为了提高性能,将每个组分成自己的组是一个好主意。

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.

现在,我将对每个集合使用相同的模式,因为它们将存储相同类型的文档。我曾经有一个单一的模型对象,因为我曾经把所有东西都放在一个集合中,但是现在我需要多个模型,每个组一个。

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.

我能想到的最好的方法是第一次创建一个模型,然后在字典中缓存模型以便快速访问。

I guess the best approach depends on the cost of creating a new Model object on each request.

我认为最好的方法取决于在每个请求上创建新模型对象的成本。

Thanks!

谢谢!

1 个解决方案

#1


20  

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:

Mongoose已经缓存了模型,您可以对多个模型/集合使用相同的模式对象。因此,只需在启动时使用以下代码创建一组模型:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({...});
var model1 = mongoose.model('model1', schema);
var model2 = mongoose.model('model2', schema);

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.

如果您不想传递model1、model2模型实例,您可以通过调用mongoose.model('model1')来查找它们。在你的处理程序。

#1


20  

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:

Mongoose已经缓存了模型,您可以对多个模型/集合使用相同的模式对象。因此,只需在启动时使用以下代码创建一组模型:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({...});
var model1 = mongoose.model('model1', schema);
var model2 = mongoose.model('model2', schema);

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.

如果您不想传递model1、model2模型实例,您可以通过调用mongoose.model('model1')来查找它们。在你的处理程序。