Search code examples
sails.jssails-mongo

Sailsjs - Prevent non-model fileds to be saved in mongo document


I recently started working with Sails and mongo. I use Sails blueprints to generate part of my api. The problem is, that the request body I send is being saved to the mongo collection, regardless of the fields defined in the model.

So for example, let's say I have the following Event model:

module.exports = {

  attributes: {

    title: {
     type: 'string',
     required: true
    },
  } 
}

When I Send a POST request to the /event/ endpoint with the following params:

{"title":"Some Event", "random":"string"}

The saved mongo document contains also the "random":"string" value, even though it's not part of the model.

I've tried to come up with some common method to remove non-model attributes before creation for all models, but the possible solutions seemed not right and dirty.

Am I missing something?

Any help would be appreciated!


Solution

  • You can use schema option in your model. Just add it to model declaration and that's it.

    // api/models/Model.js
    module.exports = {
      schema: true,
      attributes: {
        title: {
          type: 'string',
          required: true
        }
      }
    };