Last active
May 15, 2020 23:53
-
-
Save niksumeiko/f551eeb57a509bc27f9372978055c2e6 to your computer and use it in GitHub Desktop.
Mongoose schema static `findOrCreate` method in ES6/7 async/await syntax
This file contains 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
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