Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Singleton Model

I am creating a CMS for a site. There is an about page that needs to have content from the CMS. There needs to be only one document acting as a config file for the about page. My proposed solution for this is:

  1. Create an about page model.
  2. On save I will check to see if there is an existing document.
  3. If there is an existing document, update that document. If there isn't save a new one.

Is there a better way to do this? Is there a way to do this in the save pre hook for my schema ?

like image 873
pizzarob Avatar asked Jul 28 '26 00:07

pizzarob


1 Answers

Something like this could be done for a singleton model:

HomePageSchema.statics = {
 getSingleton: function (cb) {
       this.findOne()
           .sort({updated: -1})
           .limit(1)
           .exec(function (error, model) {
               if (error) {
                   cb(error, null);
               } else if (model == null) {
                   cb(error, new HomePage());
               } else {
                   cb(error, model);
               }
           });
   },
};

and then

HomePage.getSingleton((err, homepage) => {
 homepage.image = '/images/myImage.jpg';
   homepage.headline = 'Homepage Headline';
   homepage.save();
});
like image 102
pizzarob Avatar answered Jul 29 '26 14:07

pizzarob