Skip to content

Instantly share code, notes, and snippets.

@davetapley
Created April 29, 2013 16:49
Show Gist options
  • Save davetapley/5482919 to your computer and use it in GitHub Desktop.
Save davetapley/5482919 to your computer and use it in GitHub Desktop.
Validate a Mongoose model and then upsert if valid (the other way)
mySchema.statics.upsert = function (conditions, update, callback) {
this.findOne(conditions, function (err, existingDoc) {
if (err) {
callback(err);
} else if (existingDoc) {
// I don't think this is valid
existingDoc.update(update);
existingDoc.save(callback);
} else {
return this.create(update, callback);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment