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
Please use the middleware pre save as shown below.
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:
Please use the middleware pre save as shown below with a full listing of codes.
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