Created
April 29, 2013 16:49
-
-
Save davetapley/5482919 to your computer and use it in GitHub Desktop.
Validate a Mongoose model and then upsert if valid (the other way)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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