Skip to content

Instantly share code, notes, and snippets.

@tblobaum
Created September 24, 2011 05:38
Show Gist options
  • Save tblobaum/1239015 to your computer and use it in GitHub Desktop.
Save tblobaum/1239015 to your computer and use it in GitHub Desktop.
var MongooseUpserts = function (schema, options) {
options = options || {};
schema.method('removeDefaults', function () {
var paths = schema.paths;
var defaults = {};
for (var key in paths) {
if (this._doc[key] === paths[key].defaultValue) {
delete this._doc[key];
}
}
return this;
});
schema.method('upsert', function (conditions, update, callback) {
var Model = this.constructor;
var oid = Mongoose.Types.ObjectId;
var defaultConditions = {_id: this._doc._id };
var opts = options.options || {upsert: true};
delete this._doc._id;
var newDoc = this.removeDefaults().toObject();
if (typeof conditions === 'undefined') {
Model.update(defaultConditions, {$set: newDoc}, opts, function (e) {
console.log(e);
});
} else if (typeof conditions === 'function') {
Model.update(defaultConditions, {$set: newDoc}, opts, conditions);
} else if (typeof update === 'function') {
if (typeof conditions === 'string') {
Model.update(defaultConditions, {$set: newDoc}, opts, update);
} else if (/\$/.test(Object.keys(conditions).toString())) {
Model.update(defaultConditions, conditions, opts, update);
} else {
Model.update(conditions, {$set: newDoc}, opts, update);
}
} else if (typeof callback === 'function') {
Model.update(conditions, update, opts, callback);
} else {
if (typeof conditions === 'string') {
Model.update(oid.fromString(conditions), {$set: newDoc}, opts, function (e) {
console.log(e);
});
} else {
throw new Error('Invalid parameters for upsert method.');
}
}
});
};
Mongoose.plugin(MongooseUpserts, {debug:true, options: { multi: true, upsert: true }});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment