Reputation: 319
In my project I have multiple mongoose schema. The requirement is to add new property across all the schema. I want to avoid copy paste same thing across all schema. Looking for an alternative.
Thanks
Upvotes: 1
Views: 442
Reputation: 319
Achieved the above requirement, sharing common property across the schema, (extending the schema). Following are the steps,
Created an object with all common property, example,
var baseProperty = {
deleted : Boolean
createdBy : String,
updatedBy : String,
createdAt : Date,
updatedAt : Date,
};
then used in different schema in following way,
/** SCHEMA 1 **/
var userSchema = new Schema({
name : String,
mobile : String,
email : String,
}, {});
userSchema.add(baseProperty); // Injecting common property in schema
mongoose.model("User", userSchema);
/** SCHEMA 2 **/
var addressSchema = new Schema({
city : String,
state : String,
country : String,
}, {});
addressSchema.add(baseProperty); // Injecting common property in schema
mongoose.model("Address", addressSchema);
Now the above schema is ready with injected property, for CRUD operations.
Upvotes: 3