Games schema
The schema for our games will be a little more complex because of the teams
attribute. Let's start with what we know already:
*both/schemas/games.js
Games.attachSchema(new SimpleSchema({
completed: {
type: Boolean
},
ownerId: {
type: String
},
teams: {
type: [Object]
},
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
}
}));
For teams we have put type: [Object]
, which works. But what if we want to describe exactly what's in each team (name
, _id
and score
)? Luckily we can describe schemas within schemas:
both/schemas/games.js
var gameTeamSchema = new SimpleSchema({
_id: {
type: String
},
name: {
type: String
},
score: {
type: Number
}
});
Games.attachSchema(new SimpleSchema({
completed: {
type: Boolean
},
ownerId: {
type: String
},
teams: {
type: [gameTeamSchema]
},
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
}
}));
Now each individual team in our teams
attribute will need to match against our gameTeamSchema
.
Since we set createdAt
dynamically, we can go ahead and remove the code that manually sets it:
both/collections/games.js
...
var game = {
ownerId: Meteor.userId(),
teams: [teamOneData, teamTwoData],
createdAt: new Date(), // <-- REMOVE THIS LINE
completed: false
};
...
server/seeds.js
...
var game = {
completed: false,
ownerId: ownerId,
createdAt: new Date(), // <-- REMOVE THIS LINE
teams: [
{name: team1.name, _id: team1._id, score: 0},
{name: team2.name, _id: team2._id, score: 0}
]
};
...
With our schemas in place we can be much more confident about our data integrity. I suggest you create your schemas early on in your project and keep them perfectly maintained, as nothing is worse than patching up dodgy data!