Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a Mongoose Schema on the fly

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 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).

like image 262
Roxicus Avatar asked Dec 28 '22 13:12

Roxicus


2 Answers

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

schema.add({ field: Number })
like image 190
Chance Avatar answered Jan 06 '23 12:01

Chance


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 */ });
like image 45
jmar777 Avatar answered Jan 06 '23 13:01

jmar777