skip to Main Content

I want to implement a single object model in my express js and mongoose app backend.

right now i have this, how do i make it be only and only 1 object. it should not create any more than 1 data in this tabel

const mongoose = require("mongoose");

const LayoutSchema = new mongoose.Schema({
 aboutText: {
  type: String,
  trim: true,
  required: [true, "Please provide information about us."],
  maxlength: [1000, "About text should not exceed 1000 characters."],
},
 contactText: {
  type: String,
  trim: true,
  required: [true, "Please provide contact information."],
  maxlength: [1000, "Contact text should not exceed 1000 characters."],
},
    
 // Add more fields as needed
});

// Create a static method to ensure only one document exists in the collection
LayoutSchema.statics.findOneOrCreate = async function findOneOrCreate() {
 let layout = await this.findOne();
 if (!layout) {
  layout = await this.create({});
 }  return layout;
};

module.exports = mongoose.model("Layout", LayoutSchema);

Thank you in advance

i dont know how to do it and i haven’t found any good document on this subject

2

Answers


  1. Please use the middleware pre save as shown below.

      SingletonSchema.pre('save', async function () {
        const count = await SingletonModel.countDocuments();
        if (this.$isNew && count > 0) {
          throw new Error('No more addition - Singleton collection');
        }
      });
    

    Caution: Any addition of documents by findOneAndUpdate with upsert will not be stopped by the above middleware. The reason is no middleware functions including pre save will be invoked in the operation by findOneAndUpdate. For more, please refer link1 below.

    For a full listing of code, please refer to the detailed answer posted separately.

    Links:

    1. How to trigger a function for each document insertion with Mongoose?
    Login or Signup to reply.
  2. Please use the middleware pre save as shown below with a full listing of codes.

    const mongoose = require('/usr/local/lib/node_modules/mongoose');
    const { Schema } = mongoose;
    
    run();
    
    async function run() {
      await mongoose.connect('mongodb://127.0.0.1:27017/test');
    
      const SingletonSchema = new Schema({
        key1: String,
      });
    
      SingletonSchema.pre('save', async function () {
        const count = await SingletonModel.countDocuments();
        if (this.$isNew && count > 0) {
          throw new Error('No more addtion - Singleton collection');
        }
      });
    
      const SingletonModel = mongoose.model('singleton', SingletonSchema);
    
      // while running this  code for a second time,
      // the singleton check will be thrown.
      try {
        await SingletonModel.create({
          key1: 'value1',
        });
      } catch (error) {
        console.error(error);
      }
    
      // the singleton collection can be modified as below.
      const doc = await SingletonModel.findOne();
      doc.key1 = 'value1-3';
      await doc.save();
      console.log(`${await SingletonModel.find()}`);
    }
    

    Caution: Any addition of documents by findOneAndUpdate with upsert will not be stopped by the above middleware. The reason is no middleware functions including pre save will be invoked in the operation by findOneAndUpdate. For more, please refer link1 below.

    Links

    1. How to trigger a function for each document insertion with Mongoose?
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search