How we can add custom fields to mongodb database?

Viewed 147

Hello guys I need your help, I am making a simple app where users can create a post about their favorite person so there are different fields to write text, now I've made the functionality for the user to create any new field with a title of their choice like if a person "a" want to add a new field with name age and custom "b" wants to add a new field with name country, so I've made this but how can I get that custom data automatically in my database so if the user will create a new field with any name I want that field and text written in it in my database. Can you help me with that? and please try to explain to me in a simple manner am just a beginner with mongoDB. there was a guy who told me to do this with $addFields aggregation but he didn't tell me anything else I saw many documents but am not getting How can I make this done :( thank you sooooo much in advance. :)

here's my schema for default fields:

const personSchema = new Schema({
    firstName: String,
    lastName: String,
    birthDay: String,
    gender: String,
    pronouns: String,
    relationship: String,
    user: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
        username: String,
    }
});
1 Answers

You simply have to pass the strict option to false while you create your schema!

By default, mongoose will set this option to true so you can't send any unnecessary information to DB!

const personSchema = new Schema({
    firstName: String,
    lastName: String,
    birthDay: String,
    gender: String,
    pronouns: String,
    relationship: String,
    user: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
        username: String,
    }
}, { strict: false });

https://mongoosejs.com/docs/guide.html#strict

Related