How do I update a property with the current date in a Mongoose schema on every save?

前端 未结 4 953
南方客
南方客 2021-01-03 23:59

In my database collections, I want to update a \'lastChanged\' field every time the record is updated with the current datetime. I want it to be in the same format as mongoo

4条回答
  •  时光说笑
    2021-01-04 00:36

    One way of accomplishing this is to use Mongoose Middleware and update the field pre-save.

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    //schema
    var SomethingSchema = new Schema({
      text: {type: String},
      createdAt: {type: Date, default: Date.now},
      updatedAt: {type: Date, default: Date.now}
    });
    
    //middle ware in serial
    SomethingSchema.pre('save', function preSave(next){
      var something = this;
      something.updatedAt(Date.now());
      next();
    });
    

    It seems, however, that the middleware is not always invoked:

    Notes on findAndUpdate()

    pre and post are not called for update operations executed directly on the database, including Model.update,.findByIdAndUpdate,.findOneAndUpdate, .findOneAndRemove,and .findByIdAndRemove.order to utilize pre or post middleware, you should find() the document, and call the init, validate, save, or remove functions on the document. See explanation.

    Update: See this question "add created_at and updated_at fields to mongoose schemas"

提交回复
热议问题