Skip to main content

Field Aliases in Mongoose

Field Aliases in Mongoose | Rustcode

Field Aliases in Mongoose

Field aliases in Mongoose allow you to define alternate, more readable property names for fields stored in MongoDB. This is helpful when your database uses short or abbreviated property names to save space, but you want descriptive property names in your application code. Aliases improve code clarity while maintaining compact storage.


What Are Field Aliases?

  • Field aliases map a shorter stored field name in the database to a more descriptive property name in your Mongoose documents.
  • Aliases are defined in the schema at the field level using the alias option.
  • Accessing and setting the alias works like a normal property on the document.
  • The actual data is stored under the original field name in MongoDB.

Defining Aliases in Schemas

You define aliases in the schema as follows:

const personSchema = new mongoose.Schema({
  n: {
    type: String,
    alias: 'name'
  },
  a: {
    type: Number,
    alias: 'age'
  }
});

Usage of Aliases

When creating or accessing a document, use the alias property:

const Person = mongoose.model('Person', personSchema);

const person = new Person({ name: 'Alice', age: 30 });

console.log(person.n);    // Outputs: 'Alice'
console.log(person.name); // Outputs: 'Alice'

person.age = 31;
console.log(person.a);    // Outputs: 31

Advantages of Using Aliases

  • Keep database field names short for storage efficiency.
  • Use descriptive, readable property names in application code.
  • Simplify code maintenance and improve clarity.
  • Aliases work transparently with getters and setters in Mongoose.

Example: Aliasing Fields

Example showing aliases for first and last names:

const userSchema = new mongoose.Schema({
  f: { type: String, alias: 'first' },
  l: { type: String, alias: 'last' }
});

const User = mongoose.model('User', userSchema);

const user = new User({ first: 'John', last: 'Doe' });

console.log(user.f);     // John
console.log(user.last);  // Doe

Best Practices

  • Use aliases primarily to keep stored field names compact while maintaining readable code.
  • Document all aliases thoroughly to avoid confusion in team projects.
  • Be consistent in alias naming conventions to improve maintainability.
  • Remember aliases work only on the Mongoose document level, not in MongoDB queries.

Conclusion

Field aliases in Mongoose are a simple yet powerful feature for balancing database storage efficiency with code readability. By mapping short stored names to human-friendly property names, you can write cleaner, more meaningful code while saving space in your MongoDB documents.

Comments