Ismar Slomic
Ismar Slomic

Reputation: 5514

Mongoose custom schema type date interval

I have many fields in my documents of type date intervals, such as this

{
    publishDate:
    {
       start: {type: Date, required: true},
       end: {type: Date, required: true}
    }
}

To reduce duplication of the code and make it easier to maintain, how to create custom Mongoose type, for instance DateInterval, containing two fields:

  1. start
  2. end

and containing validator that makes sure both fields are filled out, and start is before end?

Upvotes: 2

Views: 1373

Answers (3)

Dario
Dario

Reputation: 4035

Since >=4.4 you can implement your custom schema type.

Documentation is not very clear, but you can follow this example.

You have to:

  • define your DateInterval custom object with toBSON() / toJSON() and toObject() prototype methods

  • define the DateIntervalType inherited from mongoose.SchemaType for handle the mongoose integration, and casting to DateInterval.

In this way you can achieve full control on memory (Mongoose model) and mongodb (raw's bson) data representation.

Upvotes: 0

Josh C.
Josh C.

Reputation: 4363

You can reuse schemas in mongoose.

var DateIntervalSchema = new Schema({
   start: {type: Date, required: true},
   end: {type: Date, required: true}
});

var SomeSchema = new Schema({
   publishDate: [DateIntervalSchema],
   // ... etc
});

You can also reference documents from other collections.

var SomeSchema = new Schema({
   publishDate: {type: Schema.ObjectId, ref: 'DateInterval'}
});    

//using populate
SomeModel.findOne({ someField: "value" })
   .populate('publishDate') // <--
   .exec(function (err, doc) {
      if (err) ...

   })

Upvotes: 3

glortho
glortho

Reputation: 13200

You'll want to develop a custom schema type. There are a number of plugins that do this already, one of which, for long numbers, can be found here: https://github.com/aheckmann/mongoose-long/blob/master/lib/index.js . This is a good basic example to follow.

For your purposes, then, you can create a DateInterval custom schema, casting it as type Date, and then use a validator to check start and end - http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate.

Upvotes: 1

Related Questions