updatedAt, createdAt
A very common scenario that Ruby on Rails users will be expecting for free is keeping track of when a document was created and last updated. These fields can be useful even if you don't show them to your users as they can help with debugging.
Collection2 allows you set an autovalue
function, which we can use to automatically set these values. A lot of this code is beyond the scope of this book, and you can check what it all means in the Collection2 documentation. I'm just allowing you to copy and paste without fully understanding the code because it's such a useful feature:
both/schemas/teams.js
Teams.attachSchema(new SimpleSchema({
name: {
type: String,
index: true,
unique: true,
max: 30
},
ownerId: {
type: String
},
gameIds: {
type: [String],
optional: true
},
createdAt: {
type: Date,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset();
}
}
},
updatedAt: {
type: Date,
autoValue: function() {
if (this.isUpdate) {
return new Date();
}
},
denyInsert: true,
optional: true
}
}));
As I said, don't worry too much about how the autovalue code works. You can test this quite easily by creating some teams and checking the data in Mongol. Try editing the team name to see the updatedAt
attribute.