Skip to content

Instantly share code, notes, and snippets.

@niksumeiko
Last active May 15, 2020 23:53
Show Gist options
  • Save niksumeiko/f551eeb57a509bc27f9372978055c2e6 to your computer and use it in GitHub Desktop.
Save niksumeiko/f551eeb57a509bc27f9372978055c2e6 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