0

I don't know if this is related to Mongoose itself or MongoDB driver.

Here is the deal. I want to add created/updated fields to my schemas. I know that Mongoose can do it out of the box, but I need to use Unix Timestamp instead of date object. To achieve this I added plugin which I had found on Github (link to plugin), and changed field type to Number to store timestamp.

I found these lines in the plugin source code:

schema.pre('update', function(next) {
    if (this.op === 'update') {
        this._update = this._update || {};
        this._update[updatedAt] = new Date().getTime;
        this._update['$setOnInsert'] = this._update['$setOnInsert'] || {};
        this._update['$setOnInsert'][createdAt] = new Date().getTime;
    }
    next();
    });

If I do

MyAwesomeModel.update(...., function (e, d) {...});

this.op will be equal to 'find', not 'update', so 'updated' field in not being changed.

I can't understand why is so, why operation is 'find' and not 'update'. I've tried to search trough mongoose source code, but to the moment I have not found the answer.

Nodari Lipartiya
  • 1,148
  • 3
  • 14
  • 24
  • Update does a regular mongo driver call. Schema.update bypass the middleware by design. Hence `.pre` does not work with `update`. You can get more details: https://github.com/Automattic/mongoose/issues/2672 – Sandip Nirmal Jul 20 '16 at 09:26

1 Answers1

0

You could ditch the plugin and use the proposed code here with Date.now() (now() return an Unix timestamp):

var ItemSchema = new Schema({
    name        : { type: String, required: true, trim: true },
    created_at  : { type: Number },
    updated_at  : { type: Number }
});

ItemSchema.pre('save', function(next){
  now = Date.now();
  this.updated_at = now;
  if ( !this.created_at ) {
    this.created_at = now;
  }
  next();
});
Community
  • 1
  • 1
Shanoor
  • 13,344
  • 2
  • 29
  • 40