在飞行中定义一个mongoose模式

我有一个模型文件,把我所有的Mongoose模型集合在一起。 我想用不定数量的字段初始化一个模型。 目前我正在定义更多的领域,而不是我想要的:

TallySchema = new mongoose.Schema 0: Number 1: Number ... 20: Number 

显然这并不理想。 我看到Mongoose会让你指定Schema定义之外的选项,但是看不到如何添加新的字段(或者我猜,在Mongoose中)。

基于mongoose插件文档 ,您可以像这样做:

 schema.add({ field: Number }) 

这将需要validation,但看看它应该是可能的来源:

在Schema构造函数中,它只是将定义对象传递给this.add() ( source )。

然后在Schema.prototype.add ( source )中创build实际的path。

所以,好像你需要做的就是这样的:

 // not sure what this looks like in CoffeeScript TallySchema.add({ /* new property definition here */ }); 

我在Mongoose文档页面中find了这个:

 var ToySchema = new Schema; ToySchema.add({ name: 'string', color: 'string', price: 'number' }); 

您可以使用“混合”types来封装您的值。 尽pipe如此,它们不可能处于最高水平,但是否则它的效果会很好。

 new mongoose.Schema({ average: Number, countPerRating: mongoose.Schema.Types.Mixed, }); 

这是一个mapreduce模式的摘录。 我使用混合types来存储某人评定的次数,所以我们可以说“10个1星评级,45个4星评级”等等。

混合型为此很好。