Skip to content

Instantly share code, notes, and snippets.

@kandros
Forked from niksumeiko/mongoose-findOrCreate.js
Created October 9, 2016 23:05
Show Gist options
  • Save kandros/362c8c7a653bec236a2efee48f24ba15 to your computer and use it in GitHub Desktop.
Save kandros/362c8c7a653bec236a2efee48f24ba15 to your computer and use it in GitHub Desktop.
Mongoose schema static `findOrCreate` method in ES6/7 async/await syntax
import mongoose from 'mongoose';
let schema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
schema.statics.findOrCreate = async (conditions, opt_attr) => {
let document = await User.findOne(conditions);
return document || await new User({ ...conditions, ...opt_attr }).save();
}
const User = mongoose.model('User', schema);
export default User;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment