简体   繁体   English

猫鼬自定义架构类型日期间隔

[英]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: 为了减少代码重复并使其易于维护,如何创建包含两个字段的自定义Mongoose类型(例如DateInterval)

  1. start 开始
  2. end 结束

and containing validator that makes sure both fields are filled out, and start is before end? 并包含确保两个字段均已填写且开始于结束之前的验证器?

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

   })

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 . 已经有许多插件可以执行此操作,其中很多可以在这里找到: 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 . 然后,出于您的目的,您可以创建一个DateInterval自定义架构,将其强制转换为Date类型,然后使用validator检查startend -http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate

Since >=4.4 you can implement your custom schema type . 由于 > = 4.4,您可以实现自定义架构类型

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 使用toBSON() / toJSON()toObject()原型方法定义DateInterval自定义对象

  • define the DateIntervalType inherited from mongoose.SchemaType for handle the mongoose integration, and casting to DateInterval . 定义DateIntervalType从继承mongoose.SchemaType用于处理猫鼬整合,铸造DateInterval

In this way you can achieve full control on memory ( Mongoose model ) and mongodb ( raw's bson ) data representation. 这样,您可以实现对内存( Mongoose模型 )和mongodb( raw的bson )数据表示的完全控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM