Skip to content

Instantly share code, notes, and snippets.

Last active May 15, 2020 23:53
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
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