Today I started to work on adding field selection capabilities to some of the endpoints used by the Auth0 app. Part of that involves updating the mongodb queries to limit the fields returned by them.
As this work will probably span a set of queries, I decided to create a module to simplify the creation of the projection objects used for the queries. That’s how mongo-select came to be:
As the mongodb documentation clearly explains, you can either
- Determine a set of fields to include by specifying their name and a related truthy value
{ name: true }
. - Determine a set of fields to exclude by specifying their name and a related falsy value
{ name: false }
.
mongo-select allows you to easily specify fields to include or exclude, both on a permanent and one time basis.
Most of the rest of this post comes from the README.md at the time of writing.
Installing
To install the latest version simply run:
Basic example
The following sample code shows how you can work with the native mongodb NodeJs driver to exclude the user field:
Including fields
To include fields use the following:
Excluding fields, no _id and chaining
You can also exclude fields using the exclude method and the _id
field using noId()
. You can chain exclusions/inclusions and noId()
. One thing to consider is that in order to provide a fluent interface the chaining methods begin with _
. Otherwise this might affect documents with fields named exclude, include, noId.
Permanent exclusion/inclusion
Sometimes it is important to always exclude or include a set of fields. That means that if they were permanently excluded and then specifically included they won’t make it into the projection and viceversa:
To clear permanent registrations simply:
Wrapping up
I’m totally up for contributions via PRs or issues, so if you have some feedback about the package or improvement ideas feel free to jump in.