Last active
December 4, 2017 17:48
-
-
Save pizzarob/34a07bd579991ff93cc1e48ded07eda7 to your computer and use it in GitHub Desktop.
Mongoose Singleton Model
This file contains hidden or 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
schema.statics = { | |
getSingleton: function (cb) { | |
this.findOne() | |
.sort({ updated: -1 }) | |
.limit(1) | |
.exec((err, model) => { | |
if (err) { | |
cb(err, null); | |
} else if (!model) { | |
cb(err, new this()); | |
} else { | |
cb(err, model); | |
} | |
}); | |
}, | |
}; | |
schema.pre('save', function (next) { | |
this.model('HomePage').find({}, (err, docs) => { | |
if (docs.length) { | |
if (docs[0]._id.toString() === this._id.toString()) { | |
return next(); | |
} else { | |
return next(new Error('Document already exists')); | |
} | |
} else { | |
next(); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment