Santosh Mondal
Santosh Mondal

Reputation: 319

How to set common property across all schema in Mongoose?

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

Answers (1)

Santosh Mondal
Santosh Mondal

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

Related Questions