Search code examples
javascriptnode.jsmongoose

Mongoose: define a schema property with one name in Document object and another in the actual database


I have in my app multiple models defined for one collection: Trainee, Employee, Contractor, Manager, and Removed.

Each model schema has a date property that represents the time the person "entered" into the status represented by the model:

const TraineeSchema = new Schema({
  ...
  accetedOn: Date,
  ...
});

const EmployeeSchema = new Schema({
  ...
  hiredOn: Date,
  ...
});

const ContractorSchema = new Schema({
  ...
  contractedOn: Date,
  ...
});

const ManagerSchema = new Schema({
  ...
  promotedOn: Date,
  ...
});

const RemovedSchema = new Schema({
  ...
  terminatedOn: Date,
  ...
});

In one case I perform an aggregation that filters data based on these properties. It would be a simpler code if all of these properties had the same name in the database. So, if for example, the data property is named enteredIntoStatusOn for all these schemas, I could just have:

{ $match: { enteredIntoStatusOn: { $gt: ... } }

Is it possible to define in a schema a property that has one name when used in a mongoose Document object, but actually saved under a different name in the database?

I know I could do something similar using aliases. For example, I could define the manager schema with the enteredIntoStatusOn defined, and then also define a virtual field named promotedOn that simply gets and sets the enteredIntoStatusOn field. But then, both promotedOn and enteredIntoStatusOn are exposed in a document for the Manager model. Is there a way in Mongoose to just have the alias without the original property?


Solution

  • The easiest way to do this is to specify an alias in the schema:

    let s = new Schema({
        n: { type: String, alias: "name" }
    });
    

    This automatically creates both getter and setter, so it is possible to use name everywhere instead of n. You can read more about aliases here.