Do you know Field Specifiers?

In this post, let’s see an important thing, especially for who is starting with Meteor. ‘Field Specifiers’.

First at all, why is ‘Field Specifiers’ so important? Two reasons, security and performance.

Security because unless you specify which fields are to be returned, MongoDB will return all of them. It means that clients can see tokens, encrypted passwords and anything else stored in your documents.

Performance. Again, if you don’t specify which fields are to be returned or not, unnecessary data will be returned to the client at inappropriate moments. Last week, believe, even with 20 post, I had performance issues, I realized that, when I accessed the main page, it tooks a long time to list posts, why? Because I was returning all the content to the list, even posts bodies, when I just had to return it.

[code language=”javascript”]

var postFieldSpecifiers = {fields: {

_id: 1,

title: 1,

language: 1,

summary: 1,

createdAt: 1,

ownerName: 1,

published: 1

}}

[/code]

You can see the code here.

Without all unnecessary information(that was the bigger part), page loading becomes fast again.

Usage.

When you use ‘Field Specifiers’, you can, exclude specific fields (0) or include just what you want (1).

For example, if you want to return everything, except password and hash, you can do something like this.

[code language=”javascript”]

Users.find({}, {fields: {password: 0, hash: 0}})

[/code]

Or if you want to return just firstname and lastname, you can do something like that.

[code language=”javascript”]

Users.find({}, {fields: {firstname: 1, lastname: 1}})

[/code]

So, if you want to exclude 0 or if you want to include 1, simple like that, one or other, you can’t mix inclusion and exclusion, except in a very specific situation; exclude _id in an inclusion specifier eg.

[code language=”javascript”]

Users.findOne({}, { fields: { firstname’: 1, _id: 0 } });

[/code]

Conclusion

‘Fields Specifiers’ ‘is’ a good practice that you should do, because it’s simple to do which brings great performance and security benefits.

Allan de Queiroz

Allan de Queiroz
London based software engineer

XServer forward from Linux text mode for Headless purposes.

Hello, this post is about XServer forward from Linux text mode, **not ssh forward, anything related to VNC** or things like that.Recently...… Continue reading