Skip to content

Instantly share code, notes, and snippets.

@jasoncrawford
Created June 27, 2013 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasoncrawford/5873309 to your computer and use it in GitHub Desktop.
Save jasoncrawford/5873309 to your computer and use it in GitHub Desktop.
Augment Mongoose with Q promises. In some cases the method is an alternative to an existing promise-returning methods, like `qexec` vs. Mongoose's native `exec`. In other cases it's providing an operation that Mongoose doesn't give promises for, such as `qsave` and `qcreate`.
var mongoose = require('mongoose');
// Workaround for the fact that chai-as-promised isn't working with Mongoose promises:
// https://github.com/domenic/chai-as-promised/issues/30
mongoose.Query.prototype.qexec = function () {
return Q.npost(this, 'exec', arguments);
}
mongoose.Model.qcreate = function () {
return Q.npost(this, 'create', arguments);
}
mongoose.Model.prototype.qsave = function () {
var deferred = Q.defer();
this.save(function (err, model) {
if (err) deferred.reject(err);
else deferred.resolve(model);
});
return deferred.promise;
}
mongoose.Model.prototype.qreload = function () {
return this.model(this.constructor.modelName).findById(this.id).qexec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment