The Sailscasts Blog

← Back to blog

sails-mongo 2.1.0

Kelvin Omereshone

In this sails-mongo release, a much requested update was merged via this PR, upgrading the MongoDB driver version from 3.7.3 to 6.3.0.

Before this update, Sails developers using MongoDB in their applications were unable to leverage the latest and greatest of MongoDB features.

This release brings about a noteworthy change by replacing callbacks with Promises in the internals of sails-mongo when interacting with the APIs provided by the MongoDB driver.

Also see the full changelog on GitHub.

✅ Upgrading

To upgrade to sails-mongo 2.1.0, run:

npm i sails-mongo@latest

Updating your code

When interacting with the MongoDB client provided by sails-mongo in your Sails applications, it is essential to transition from callbacks to promises. This can be achieved through either .then() calls or using the async/await syntax.

To minimize alterations to your existing codebase, we suggest employing an Immediately Invoked Function Expression (IIFE) to encapsulate the Promise’s .then() and .catch() methods. This way, your callbacks can stay unaltered. The following example is extracted from the test in sails-mongo.

Before ❌

it('should find a record w/ a numeric ID', function(done) {
  models.user._adapter.datastores.test.manager.collection('user').insertOne({_id: 123, name: 'bob'}, function(err) {
    if (err) {return done(err);}
    models.user.findOne({id: 123}).exec(function(err, record) {
      if (err) {return done(err);}
      assert.equal(record.id, 123);
      assert.equal(record.name, 'bob');
      return done();
    });
  });
});

After ✅

it('should find a record w/ a numeric ID', function(done) {
  (function(iifeDone) {models.user._adapter.datastores.test.manager.collection('user').insertOne({_id: 123, name: 'bob'}).then(function(){ iifeDone();}).catch(function(err) { iifeDone(err);});})(function(err) {
    if (err) {return done(err);}
    models.user.findOne({id: 123}).exec(function(err, record) {
      if (err) {return done(err);}
      assert.equal(record.id, 123);
      assert.equal(record.name, 'bob');
      return done();
    });
  });
});