Question

My schema has properties foo and bar. It is only allowed that one or the other exist when the document is saved. Not none, not both.

var schema = mongoose.Schema({
    foo: { type: ObjectId, ref: 'Foo' },
    bar: { type: ObjectId, ref: 'Bar'}
  });

Is there a way for me to mark these fields required in such an 'exclusive or' way, or do I need to implement this save logic myself?

Was it helpful?

Solution

Use mongoose Schema Pre-save event to test for existence of one or another before mongoose executes the actual save.

schema.pre('save', function (next) {
  // do stuff
  next();
});

http://mongoosejs.com/docs/middleware.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top