Erik
Erik

Reputation: 14750

How to share enum values in mongoose shema?

I have mongoose schema with the following enum values:

kind: { type: Number, enum: [0, 1, 2, 3, 5, 10, 11] }

And in some of my router I need to use one of these value like the following:

Model.create({kind: 10}).exec(callback);

The problem I'm faced with is using number 10 instead symbolic name. So what is the best way to share named constants and use bith in shema and routes?

Upvotes: 2

Views: 642

Answers (2)

L. Meyer
L. Meyer

Reputation: 3253

I like to attach them with the model:

const ENUM = {
  ONE: 1,
  TWO: 2,
  TEN: 10
};

const kindSchema = new Schema({
  kind: { type: Number, enum: _.values(ENUM) }
});

kindSchema.statics.KINDS = ENUM;

Model.create({ kind: Model.KINDS.TEN });

Upvotes: 4

alexmac
alexmac

Reputation: 19607

You can define const for each kind, and use it in both: schema and router:

// consts.js
const KIND0 = 0;
const KIND1 = 1;
...
const KIND10 = 1;
const KINDS = [KIND0, KIND1,...,KIND10];

// schema.js
kind: {
  type: Number,
  enum: KINDS
}

// router.js
Model.create({ kind: KIND10 }).exec(callback);

Upvotes: 2

Related Questions