Step one: Define your schema
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const mySchema = new Schema({
title: {type: String, required: true},
description: String
}, {collection: 'MyModel', timestamp: true});
Step two: Add a static method to your schema
mySchema.statics.findOneOrCreate = function findOneOrCreate(condition, doc) {
const self = this;
const newDocument = doc;
return new Promise((resolve, reject) => {
return self.findOne(condition)
.then((result) => {
if (result) {
return resolve(result);
}
return self.create(newDocument)
.then((result) => {
return resolve(result);
}).catch((error) => {
return reject(error);
}) }).catch((error) => {
return reject(error);
})
});
};
Step 3: Export your model
export default mongoose.model('MyModel', mySchema);
Originally published at medium.com on April 23, 2018.
🌎 Let’s keep in touch
Subscribe on YouTube
Discord
Twitter
TikTok
FaceBook
Instagram
Buy me a Coffee