The importance of data validation in MEAN apps

If when do not use data validation in MEAN apps, we will probably get unexpected and unwanted results.

Consider the following schema:


{
    name: String,
    items: Array
}

items is an array of objects. It should contain objects structured as follows:


{
  title: 'Test',
  value: 5
}

In one of our API routes we get an unexpected error:


app.get('/api/documents/titles', function(req, res) {
    Docs.find().sort({name: 1}).then(function(results) {
      let titles = [];
      results.forEach(function(result) {
         let items = result.items;
         items.forEach(function(item) {
             titles.push(item.title.toLowerCase()); // Error 502
         });
      });
      res.json(titles);
    }).catch(function(err) {
        res.json(err);
    });
});

After inspecting our collection in the MongoDB console, we notice something that we don't like much:


[
    {
        title: 'Test',
        value: 5
    },
    {
        title: null,
        value: 8
    }
]

As you can see, we tried to invoke .toLowerCase() on a null value, hence the returned error. This kind of values are quite common when an app is designed to accept input from users. Instead of trying to implement validation routines only on the client side, we can take advantage of MongoDB document schemas to protect our database from unwanted data.

So our initial schema now becomes:


{
    name: String,
    items: [
      {
          title: String,
          value: Number
      }
    ]
}

Now MongoDB drivers, such as Mongoose, will raise an exception when you try to save a document that doesn't meet the specified criteria.

Prev Articles Next