简体   繁体   中英

Update date inside mongoose schema every time

I'm trying to update the lastMessageAt every time the [messageSchema] is updated.

It doesn't work this way. I The only date that is generated when the messageSchema is filled with it's very first object.

How do i solve this?

Thanks in advance!

const chatSchema = new mongoose.Schema({
  userName1: String,
  userName2: String,
  messages: [messageSchema],
  lastMessageAt: {
    type: Date,
    default: Date.now
  }
});

You could use mongooses post middleware.

chatSchema.post('save', function(next) {
  if (this.isModified('messages')) {
    this.lastMessageAt = Date.now();
  }
  next();
});

found out that mongoose now has built in timestamps and they are used like this:

const chatSchema = new mongoose.Schema(
  {
    userName1: String,
    userName2: String,
    messages: [messageSchema]
  },
  { timestamps: true }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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