The Latest in Mongoose 2.x
Mongoose is now at version 2.6.0 so I thought I’d share a few features that have been added in recent weeks that you may have missed in the release notes.
Default Path Selection
If your schema has paths that tend to contain large amounts of data, say images stored as Buffers that are rarely needed in your application, Mongoose now provides the select schema option which allows you to exclude that field from all of your queries by default.
new Schema({ img: { type: Buffer, select: false }})Now, when you query your collection, the img field will not be included.
Products.findById(id, cb);
function cb (err, product) {
if (err) // handle err
console.log(product.img) // undefined
});To get the img back you may select the field normally:
Products.findById(id).select('img name etc').exec(cb);
function cb (err, product) {
if (err) // handle err
console.log(product.img) // binary data
});Getter/Setter SchemaType Introspection
Getters and setters are now passed their parent SchemaType giving them the ability to tailor logic based on options specified in your schema. For example, say you want to set the default title when a special value is passed:
// create a schema with a default title
new Schema({ title: {
type: String
, default: 'Please enter a title'
, set: setter
}})
// our setter that returns the default value if
// '-reset' is passed
function setter (val, type) {
if ('-reset' == val)
return type.getDefault(this);
return val;
}
// generate our model
var Model = db.model('IntrospectionExample', schema);
// create an instance
var m = new Model({ title: 'Avengers' });
// see it in action
console.log(m.title) // 'Avengers'
m.title = '-reset';
console.log(m.title) // 'Please enter a title' :DThe same is true for getters.
Tailable Queries
Queries now have the tailable option which lets us tail a collection much like the Unix tail -f command.
var stream = Model.find().tailable().stream();
Tailable queries can only be used on capped collections, can only return documents in their natural order, and never use indexes. Unless the cursor dies, a tailable QueryStream will remain open and receive documents as they are inserted into the collection. Check out this gist for an example.
You Rock
Much of what happens in Mongoose is driven directly by your code and suggestions. If you have thoughts or ideas about Mongoose, stop by our Google Group and chime in, or if you want to really make a difference, write a bug fix and open a pull request!
The Future
Features for the 2.x branch are winding down (but not bugfixes) while we move closer towards a 3.0 release. Stay tuned for an upcoming post about the Mongoose roadmap and our vision for the future of Node and MongoDB.