1

I have the following schema:

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

I'd like to somehow have another field, createdAt, which populates using doc._id.getTimestamp(). That way I don't have to inject that value every time a user queries this collection. How would I achieve this?

ffxsam
  • 26,428
  • 32
  • 94
  • 144
  • Take a look here: https://stackoverflow.com/questions/12669615/add-created-at-and-updated-at-fields-to-mongoose-schemas – Mike Kozak May 24 '17 at 01:00

1 Answers1

0

You could use a pre-save hook:

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();
});

You'd have to make sure that doc._id.getTimestamp() is accessible from the schema or set it up as an instance method:

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

...and then call it in your pre-save hook:

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

In this case you could also use the schema options object to set up time stamps which will populate automatically:

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

You can name your timestamps like so:

createdAt: 'timestampName'
Steve Holgado
  • 11,508
  • 3
  • 24
  • 32