开发者

Defining a Mongoose Schema on the fly

开发者 https://www.devze.com 2023-04-06 22:35 出处:网络
I have a model file that gathers together all my Mongoose models. One of the models I would like to initialize with a variable number of fields. Currently I\'m defining more fields开发者_如何学C than

I have a model file that gathers together all my Mongoose models. One of the models I would like to initialize with a variable number of fields. Currently I'm defining more fields开发者_如何学C than I think I am going to require:

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

Obviously this is not ideal. I see Mongoose will let you specify options outside the Schema definition but can't see how to add new fields (or paths, I guess, in Mongoose).


Based on the mongoose plugin documentation it looks like you can just do:

schema.add({ field: Number })


This would need to be verified, but looking at the source it should be possible:

In the Schema constructor, it simply passes the definition object to this.add() (source).

The actual paths then get created within Schema.prototype.add (source).

So, seems like all you would need to do is something like:

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


I found this in the Mongoose documentation page:

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


You can use the 'mixed' type to encapsulate your values. It wouldn't be possible to have them be at the top level though but it works great otherwise.

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

This is an excerpt from a mapreduce schema. I use the mixed type to store the number of times someone gives a certain rating, so we can say things like "10 1 star ratings, 45 4 star ratings", etc.

mixed type worked great for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号