How to modify mongoose schema dynamically, i have to add dynamic fields that are not defined in initial mongoose Schema

Viewed 1240

This is the existing schema, in my Node App, where i have declared all the filed in Schema

const userSchema = new mongoose.Schema({
  username: String,
  password: String,
  interests: String
});

Which Creates the following document

{ 
    "_id" : ObjectId("60edab731ba3623280f4aead"), 
    "username" : "a@a.com", 
    "hash" : "4753f142aac6f912812d1cc79", 
    "__v" : NumberInt(0), 
    "interests" : "Fishing, Reading"
}

Now i have added more fields for users like Education, Age, Profile Photo & so on, output document should look like below.

{ 
    "_id" : ObjectId("60edab731ba3623280f4aead"), 
    "username" : "a@a.com", 
    "hash" : "4753f142aac6f912812d1cc79", 
    "__v" : NumberInt(0), 
    "interest1" : "Fishing",
    "education" : "Some Edutation",
    "age" : 35,
    "profile_pic": "https://image-link.jpg"
}

Easiest solution would be to go back and update the schema to required fields manually like below

   const userSchema = new mongoose.Schema({
      username: String,
      password: String,
      interests: String,
      education: String,
      age: Number,
      profile_pic: String
    });

But how do this dynamically, so that i can add new data to document on the fly & create new filed if it doesn't exist in the schema? i know if use mongoDB directly i don't have to worry about Schemas but i am using Mongoose here

1 Answers

You can use .add Method

userSchema.add({education: String, age: Number, profile_pic: String});

Checkout Mongoose Schema.prototype.add()

Related