Skip to content

Instantly share code, notes, and snippets.

@pizzarob
Last active December 4, 2017 17:48
Show Gist options
  • Save pizzarob/34a07bd579991ff93cc1e48ded07eda7 to your computer and use it in GitHub Desktop.
Save pizzarob/34a07bd579991ff93cc1e48ded07eda7 to your computer and use it in GitHub Desktop.
Mongoose Singleton Model
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