Mongoose 3.6 Release Notes

The primary focus of the 3.6 release was a rewrite and expansion of the query population feature. Population capabilities are now far more robust, flexible, and perform much faster than before. Also of significant note are additional new features in support of MongoDB 2.4. What follows are the details of all 58 new features, enhancements, and bug fixes.

Population

Added Model.populate(docs, opts, cb)

The core population functionality has been rewritten and exposed through Model.populate(docs, paths, cb). This refactor and exposure opens the door to populating plain js objects as well as mongoose documents, meaning population of documents returned from lean queries and mapReduce output is supported.

While not directly supported through the query.populate() syntax, recursive population of multi-level deep refs can be achieved by calling Model.populate ad infinitum to populate structures that span more than 2 collections. Check out this gist for an example.

Query.populate now accepts an options object

populate accepts up to five arguments making it a bit obscure what is each argument is when all are passed. We now support an options object which clarifies the arguments and allows applying several options to more than one path at a time.

  1. // old (still supported)
  2. Model
  3. .find()
  4. .populate('friends', 'name age', 'ModelName', { age: { $gte: 18 }}, { sort: { age: -1 }})
  5. .populate('author', 'name age', 'ModelName', { age: { $gte: 18 }}, { sort: { age: -1 }})
  6. // new
  7. Model.find().populate({
  8. path: 'friends author' // either single path or multiple space delimited paths
  9. , select: 'name age' // optional
  10. , model: 'ModelName' // optional
  11. , match: { age: { $gte: 18 }} // optional
  12. , options: { sort: { age: -1 }} // optional
  13. })

Added document.populate(opts | path, [cb])

Documents themselves now support population.

  1. Model.findById(id, function (err, doc) {
  2. doc
  3. .populate('owner')
  4. .populate({ path: 'friends', select: 'name' }, function (err, pop) {
  5. console.log(pop.owner.name)
  6. assert.equal(doc.id, pop.id) // same doc
  7. })
  8. })

The document passed to the callback is the same as the document that executed populate().

Added document.populated(path)

Returns original _id(s) used in population call for that path. If the path was not populated, undefined is returned.

  1. Model.findOne(function (err, doc) {
  2. console.log(doc.comments) // [ObjectId('xxx'), ObjectId('yyy')]
  3. doc.populate('comments', function (err, doc) {
  4. console.log(doc.comments) // [{ _id: ObjectId('xxx'), name: 'populated' }, { _id: ObjectId('yyy') }]
  5. console.log(doc.populated('comments')) // [ObjectId('xxx'), ObjectId('yyy')]
  6. })
  7. })

Syntax support for population of multiple fields

  1. Model.find().populate('owner comments friends').exec(callback)
  2. document.populate('owner comments friends', callback)
  3. Model.populate(docs, 'owner comments friends', callback)

Specifying identical options for all paths:

  1. var opts = { path: 'owner comments friends', select: 'name' }
  2. Model.find().populate(opts).exec(callback)
  3. document.populate(opts, callback)
  4. Model.populate(docs, opts, callback)

Separate options per path:

  1. var opts = [
  2. { path: 'owner', select: 'name' }
  3. , { path: 'comments', select: 'title -body', match: { createdAt: { $gt: lastMonth }}}
  4. , { path: 'friends', options: { sort: { name:-1 }}}
  5. ]
  6. Model.find().populate(opts).exec(callback)
  7. document.populate(opts, callback)
  8. Model.populate(docs, opts, callback)

Improved population support for arrays within arrays

Arrays within arrays are now able to be populated:

  1. var schema = new Schema({
  2. name: String
  3. , em: [{ arr: [{ person: { type: Schema.ObjectId, ref: 'Person'}}] }]
  4. });
  5. A.findById(id).populate('em.arr.person').exec(function (err, doc) {
  6. console.log(doc.em[0].arr[0].person instanceof mongoose.Document) // true
  7. })

Support adding documents to populated paths

Change from 3.5.x

Previously, setting a populated path to a document, or adding a document to a populated array would cause the document to be cast back to an _id. This is now fixed and the argument is cast to a document.

#570

  1. Model.findOne().populate('owner comments').exec(function (err, doc) {
  2. console.log(doc.owner) // a populated document
  3. doc.owner = { name: 'a different document' }
  4. console.log(doc.owner) // { _id: 'xxx', name: 'a different document' }
  5. assert(doc.owner instanceof mongoose.Document) // true
  6. console.log(doc.comments) // an array of populated documents
  7. doc.comments.push({ body: 'a new comment' })
  8. var added = doc.comments[doc.comments.length - 1]
  9. console.log(added) // { _id: 'xxx', body: 'a new comment' }
  10. assert(added instanceof mongoose.Document) // true
  11. })

Support population in combination with lean() queries

Previously, we could not combine lean() with populate(). For example, this would fail to populate batch:

#1260

  1. Model.find().lean().populate('batch').exec(fn)

Support population of non-schema ad-hoc paths

Populating paths that are not defined in the schema is now possible as long as the model name is passed. This is particularly helpful for populating mapReduce results and opens the door to do things with the aggregation framework in the future.

  1. Model.populate({ friend: 4815162342 }, { path: 'friend', model: 'ModelName' }, callback);

Population performance improvements

The refactor of populate brought with it opportunities for performance improvements. Here are some very non-scientific benchmarks run on my MacBook Air using node.js 0.8.21.

  1. node populate.js 1
  2. ==================================
  3. 3.5.7: 8117 completed queries
  4. 3.6.0-rc1: 11226 completed queries
  5. node populate.js 10
  6. ==================================
  7. 3.5.7: 1662
  8. 3.6.0-rc1: 4200
  9. node populate.js 20
  10. ==================================
  11. 3.5.7: 898
  12. 3.6.0-rc1: 2376
  13. node populate.js 50
  14. ==================================
  15. 3.5.7: 370
  16. 3.6.0-rc1: 1088
  17. node populate.js 100
  18. ==================================
  19. 3.5.7: 188
  20. 3.6.0-rc1: 590

Prevent potentially destructive operations on populated arrays

When saving a document with an array populated using a query condition, skip and/or limit options, or exclusion of the _id property, we now produce an error if the modification to the array results in either a $set of the entire array or a $pop. Reason: the view mongoose has of the array has diverged from the array in the database and these operations would have unknown consequences on that data. Use doc.update() or Model.update() instead. See the commit for more information and examples.

Prevent updates to $elemMatch projected arrays

Similar to why potentially destructive array operations are disallowed, we now also disallow modifications made to arrays selected using the $elemMatch projection. The view mongoose has of the array has diverged from what is in the database and these operations would have unknown consequences as a result. Use doc.update() or Model.update() instead.

Validation errors now include values

Example:

  1. var schema = Schema({ age: { type: Number, min: 18 }})
  2. var M = mongoose.model('Model', schema);
  3. var doc = new M({ age: 4 });
  4. doc.save(function (err) {
  5. console.log(err) // ValidationError: Validator "min" failed for path name with value `4`
  6. console.log(err.errors.age.value) // 4
  7. })

Refactor internal document properties and methods

To allow greater flexibility in designing your document schemas, mongoose internal properties are no longer littered everywhere and private methods have been renamed with a $ prefix (document property names cannot begin with $ in MongoDB) to avoid naming collisions. The exception is the private init method which remains to facilitate pre('init') hooks.

Support for non-strict document.set() and Model.update()

The schemas strict option can now be optionally overridden during document.set() and Model.update(). This is helpful when cleaning up old properties that are no longer in the schema.

  1. // set
  2. document.set('path', value, { strict: false })
  3. // update
  4. Model.update(selector, doc, { strict: false })

Object literal schema support

mongoose.model() and connection.model() now support passing an object literal schema. Useful for quick scripts, etc.

  1. mongoose.model('Name', { object: { literal: Boolean }})

Auto-generated ObjectIds support

Set the auto option to true to create an ObjectId at document construction time automatically.

#1285

  1. var M = mongoose.model('Blog', { owner: { type: Schema.Types.ObjectId, auto: true }})
  2. var m = new M;
  3. console.log(m.owner) // ObjectId('513f5f7a2b4024250053bec8')

Improved sub-document schema types declaration

Passing a capitalized type as a string is now supported.

  1. new Schema({ path: [{ type: 'String' }] });

Support optional command buffering

When running with the drivers autoReconnect option disabled and connected to a single mongod (non-replica-set), mongoose buffers commands when the connection goes down until you manually reconnect. To disable mongoose buffering under these conditions, set this option to false. Note: by default, both autoReconnect and bufferCommands are true.

  1. mongoose.connect(uri, { server: { autoReconnect: false }});
  2. new Schema({ stuff: String }, { bufferCommands: false });

Improve Boolean casting

The strings ‘true’ and ‘false’ now cast to the Boolean true and false respectively.

  1. var schema = Schema({ deleted: Boolean })
  2. var M = mongoose.model('Media', schema)
  3. var doc = new M({ deleted: 'false' })
  4. assert(false === doc.deleted)

Support nulls in arrays of Buffer

For consistency between all array types, buffer arrays now accept null values too.

  1. Schema({ buffers: [Buffer] })
  2. new Doc({ buffers: [new Buffer(0), null, new Buffer('supported')] })

Support doc.array.remove(non-object value)

Passing the _id directly to documentArray#remove() now works, instead of needing to pass { _id: value }.

#1278

  1. doc.array.remove('513f5f7a2b4024250053bec8') // now same as
  2. doc.array.remove({ _id: '513f5f7a2b4024250053bec8' })

Add transform option for QueryStreams

We may want to transform a document before it is emitted on data to convert it to a string for example.

  1. // JSON.stringify all documents before emitting
  2. var stream = Thing.find().stream({ transform: JSON.stringify });
  3. stream.pipe(writeStream);

Expose list of added model names

#1362

  1. mongoose.model('Thing', aSchema);
  2. console.log(mongoose.modelNames()) // ['Thing']
  3. var conn = mongoose.createConnection();
  4. conn.model('Thing2', aSchema);
  5. conn.model('Thing3', anotherSchema);
  6. console.log(connection.modelNames()) // ['Thing2', 'Thing3']

Expose mongoose constructors to all Mongoose instances

Previously, when creating more instances of Mongoose, the various mongoose constructors were not exposed the same way they are through the module itself. This has been fixed. Example:

  1. var mongoose = require('mongoose');
  2. console.log(typeof mongoose.Document) // function
  3. var mongoose2 = new mongoose.Mongoose;
  4. // old
  5. console.log(typeof mongoose2.Document) // undefined
  6. // mongoose 3.6
  7. console.log(typeof mongoose2.Document) // function

Hashed indexes support (MongoDB >= 2.4)

MongoDB 2.4 supports a new type of index called hashed indexes. We may enable it as follows:

  1. Schema({ someProp: { type: String, index: 'hashed' }})
  2. // or
  3. schema.index({ something: 'hashed' })

GeoJSON support (MongoDB >= 2.4)

MongoDB 2.4 supports GeoJSON. In support of GeoJSON, mongoose 3.6 has the following new features:

2dsphere indexes

  1. new Schema({ loc: { type: [Number], index: '2dsphere'}})
  2. // or
  3. schema.index({ line: '2dsphere' })

$geoIntersects

Casting of GeoJSON coordinates.

  1. var geojsonLine = { type: 'LineString', coordinates: [[180.0, 11.0], [180.0, '9.00']] }
  2. Model.find({ line: { $geoIntersects: { $geometry: geojsonLine }}}, callback);

You might also notice the new $geometry operator is supported.

query.intersects.geometry()

Similar to the $geoIntersects example above, the mongoose Query builder now supports an intersects getter and geometry() method for a more fluid query declaration:

  1. Model.where('line').intersects.geometry(geojsonLine).exec(cb);

query.within.geometry()

$within supports the $geometry operator as well.

  1. var geojsonPoly = { type: 'Polygon', coordinates: [[[-5,-5], ['-5',5], [5,5], [5,-5],[-5,'-5']]] }
  2. Model.find({ loc: { $within: { $geometry: geojsonPoly }}})
  3. // or
  4. Model.where('loc').within.geometry(geojsonPoly)

For more information about MongoDB GeoJSON, read the 2.4 pre-release notes.

array $push with $each, $slice, and $sort (MongoDB >= 2.4)

Mongoose 3.6 supports these new MongoDB 2.4 array operators.

  1. Model.update(matcher, { $push: { docs: { $each: [{ x: 1 }, { x: 23 }, { x: 5 }], $slice: -2, $sort: { x: 1 }}}})

Support $setOnInsert (MongoDB >= 2.4)

Mongoose 3.6 supports the MongoDB 2.4 $setOnInsert operator for upserts.

Support authSource

Support for the authSource driver option (driver version 1.2.14) is now supported.

  1. mongoose.connect('mongodb://user:pass@host:27017/db?authSource=databaseName')
  2. // or
  3. mongoose.connect(uri, { auth: { authSource: 'databaseName' }})

Promises A+ 1.2 conformant

The promise module has now been refactored and published separately with support for version 1.2 of the Promises A+ spec.

Added promise.then(onFulfill, onReject)

then creates and returns a new promise which is “tied” to the original promise (read the spec). If onFulfill or onReject are passed, they are added as success/error callbacks to this promise after the nextTick. See the spec for the full rundown.

  1. var promise = Model.findOne({ version: '3.6' }).exec();
  2. promise.then(function (doc) {
  3. console.log('the version is %s', doc.version);
  4. }, function (err) {
  5. console.error('awww shucks', err)
  6. })

Added promise.end()

end signifies that this promise was the last in a chain of then() calls. This is useful when no onReject handler has been registered and a handler passed to then() throws, in which case the exception would be silently swallowed. Declaring an end() to your then() calls allows the error to go uncaught.

  1. var p = Model.findOne({ version: '3.6' }).exec();
  2. p.then(function(){ throw new Error('shucks') });
  3. setTimeout(function () {
  4. p.fulfill();
  5. }, 10);
  6. // error was caught and swallowed by the promise returned from
  7. // p.then(). we either have to always register handlers on
  8. // the returned promises OR we can do the following...
  9. // this time we use .end() which prevents catching thrown errors
  10. var p = Model.findOne({ version: '3.6' }).exec();
  11. var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--
  12. setTimeout(function () {
  13. p.fulfill(); // throws "shucks"
  14. }, 10);

For more information, read the mongoose promise docs, the mpromise docs and the Promises A+ docs.

Bug fixes

  • fixed; lean population #1382
  • fixed; empty object mixed defaults now return unique empty objects #1380 change from 3.5
  • fixed; populate w/ deselected _id using string syntax
  • fixed; attempted save of divergent populated arrays #1334 related
  • fixed; better error msg when attempting use of toObject as property name
  • fixed; setting populated paths #570
  • fixed; casting when added docs to populated arrays #570
  • fixed; prevent updating arrays selected with $elemMatch #1334
  • fixed; pull/set subdoc combination #1303
  • fixed; multiple background index creation #1365
  • fixed; manual reconnection to single mongod
  • fixed; Constructor / version exposure #1124
  • fixed; CastError race condition
  • fixed; no longer swallowing misuse of subdoc#invalidate()
  • fixed; utils.clone retains RegExp opts
  • fixed; population of non-schema properties
  • fixed; allow updating versionKey #1265
  • fixed; add EventEmitter props to reserved paths #1338
  • fixed; can now deselect populated doc _ids #1331
  • fixed; properly pass subtype to Binary in MongooseBuffer
  • fixed; casting to _id from document with non-ObjectId _id
  • fixed; schema type edge case { path: [{type: "String" }] }
  • fixed; typo in schemadate #1329 jplock

Updated

  • driver to version 1.2.14

Deprecated

  • deprecated; collection name pluralization

    The collection name pluralization rules are confusing. We generally expect that model names are used for collection names without alteration. Though deprecated, the rules will stay in effect until 4.x.