如何以编程方式填充Mongoose模型字段?

时间:2017-05-24 00:38:57

标签: javascript mongoose mongoose-schema

我有以下架构:

const geoframeSchema = mongoose.Schema({
  count: Number,
  createdBy: String,
  polygons: [
    {
      points: [{ lat: Number, lng: Number }],
    },
  ],
});

我想以某种方式拥有另一个字段createdAt,该字段使用doc._id.getTimestamp()填充。这样,每次用户查询此集合时,我都不必注入该值。我怎么做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用预保存挂钩:

const geoframeSchema = mongoose.Schema({
    count: Number,
    createdBy: String,
    createdAt: Date,
    polygons: [
        {
            points: [{ lat: Number, lng: Number }],
        },
    ],
});

geoframeSchema.pre('save', function() {
    this.createdAt = doc._id.getTimestamp();
});

您必须确保可以从架构访问doc._id.getTimestamp()或将其设置为实例方法:

geoframeSchema.methods.getTimestamp = function() {
    ...
}

...然后在预保存挂钩中调用它:

geoframeSchema.pre('save', function() {
    this.createdAt = this.getTimestamp();
});

在这种情况下,您还可以使用架构选项对象来设置将自动填充的时间戳:

const geoframeSchema = mongoose.Schema({
    count: Number,
    createdBy: String,
    polygons: [
        {
            points: [{ lat: Number, lng: Number }],
        },
    ],
}, {
    timestamps: {
        createdAt: 'createdAt',
        updatedAt: 'updatedAt'
    }
});

您可以将时间戳命名为:

createdAt: 'timestampName'