Data integrity
Since Mongo allows you to just store JSON it's very easy to add/remove extra attributes or change the type of data. For example, maybe something is always meant to be a number but you accidentally write code that updates the field as a string. Or maybe you called a field "title" in one part of your app, but accidently call it "name" in another part of your app. For example:
Data without integrity
// Here we set the age as an number
Meteor.users.update({_id: 'BnivD427FGzq4DA9s'}, {$set: {age: 27}});
// This changes the age to a String
Meteor.users.update({_id: 'BnivD427FGzq4DA9s'}, {$set: {age: "27"}});
To avoid this we need to validate the data when making changes to the database. So if we want a user's age to always be an number we can write a rule saying the data type of age
should always be Number
.
While we should also perform validation on the client (form validation), our main priority here is validation on the server (checking against a schema). You can't rely on just client validation as users can get around that (eg. by using the Chrome console).
Collection2 solves the issue of server validation by allowing you to create 'schemas' for your collections. A schema is just like a description of your collection - a set of rules describing what attributes are in it. For example:
Example schema
var schema = new SimpleSchema({
name: {
type: String,
label: "Your name",
max: 50
},
email: {
type: String,
regEx: SimpleSchema.RegEx.Email,
label: "E-mail address"
},
message: {
type: String,
label: "Message",
max: 1000
}
});
If we add the above schema to a collection, it will enforce these rules when you try and edit the collection. So for new records it will expect a name
, an email
, and a message
. The name
HAS to be a String
, and can't be more than 50 characters. The email
must match the regular expression (which is provided by the Collection2). And the message
can't be longer than 1000 characters. There are many more types of rules you can add too.