Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose use only createdAt timestamp

I have the following message schema in mongoose:

var messageSchema = mongoose.Schema({
  userID: { type: ObjectId, required: true, ref: 'User' },
  text:   { type: String, required: true }
},
{
  timestamps: true
});

Is there anyway to ignore the updatedAt timestamp? Messages won't be updated so updatedAt will be wasted space

like image 692
Juan Fuentes Avatar asked Aug 11 '16 20:08

Juan Fuentes


Video Answer


2 Answers

Maybe even better with Mongoose v5 is to do the following;

const schema = new Schema({   // Your schema... }, {   timestamps: { createdAt: true, updatedAt: false } }) 
like image 176
robinvdvleuten Avatar answered Sep 18 '22 14:09

robinvdvleuten


Edit I've amended the answer to reflect the better option to use the default as per @JohnnyHK

You can handle this yourself by declaring the createdAt (or whatever you want to call it) in your schema:

mongoose.Schema({
  created: { type: Date, default: Date.now }
  ...

Alternatively we can also update values on new document in a pre save hook:

messageSchema.pre('save', function (next) {
  if (!this.created) this.created = new Date;
  next();
})

Along those lines is also the flag isNew which you can use to check if a document is new.

messageSchema.pre('save', function (next) {
  if (this.isNew) this.created = new Date;
  next();
})
like image 33
cyberwombat Avatar answered Sep 16 '22 14:09

cyberwombat