Chris Wilson Chris Wilson - 3 months ago 12
Node.js Question

Sails.js not applying model scheme when using MongoDB

I'm going through the (excellent) Sails.js book, which discusses creating a User model

User.js
in Chapter 6 like so:

module.exports = {
connection: "needaword_postgresql",
migrate: 'drop',
attributes: {
email: {
type: 'string',
email: "true",
unique: 'string'
},

username: {
type: 'string',
unique: 'string'
},

encryptedPassword: {
type: 'string'
},

gravatarURL: {
type: 'string'
},

deleted: {
type: 'boolean'
},

admin: {
type: 'boolean'
},

banned: {
type: 'boolean'
}
},
toJSON: function() {
var modelAttributes = this.toObject();
delete modelAttributes.password;
delete modelAttributes.confirmation;
delete modelAttributes.encryptedPassword;
return modelAttributes;
}
};


Using Postgres, a new record correctly populates the boolean fields not submitted by the login form as null, as the book suggests should be the case:

enter image description here

But I want to use MongoDB instead of PostgreSQL. I had no problem switching the adaptor. But now, when I create a new record, it appears to ignore the schema in
User.js
and just put the literal POST data into the DB:

enter image description here

I understand that MongoDB is NoSQL and can take any parameters, but I was under the impression that using a schema in
Users.js
would apply to a POST request to the
/user
endpoint (via the blueprint routes for now) regardless of what database was sitting at the bottom. Do I need to somehow explicitly tie the model to the endpoint for NoSQL databases?

(I've checked the records that are created in Postgres and MongoDB, and they match the responses from localhost:1337/user posted above)

Answer

I understand that MongoDB is NoSQL

Good! In sails the sails-mongo waterline module is responsible for everything regarding mongodb. I think I found the relevant code: https://github.com/balderdashy/sails-mongo/blob/master/lib/document.js#L95 So sails-mongo simply does not care about non existent values. If you think this is bad then feel free to create an issue on the github page.

A possible workaround might be using defaultsTo:

banned : {
    type : "boolean",
    defaultsTo : false
}