Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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