Sling Academy
Home/Node.js/How to Use Field Aliases in Mongoose

How to Use Field Aliases in Mongoose

Last updated: December 30, 2023

Overview

Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js which provides a high-level schema-based solution for model application data. In this tutorial, we’ll explore how to utilize field aliases in Mongoose to create more readable and manageable database interactions.

Field aliases in Mongoose allow you to map document fields to different names in your schema model. This can simplify interactions with your model, as you can use short, concise names for fields when working through your application code while still storing documents with more descriptive field names in MongoDB.

Basic Alias Setup

Here’s how you can set up a simple alias in a Mongoose schema:

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  fn: { type: String, alias: 'firstName' }
});

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

// You can now use both 'fn' and 'firstName' to refer to the same field

Creating and Querying with Aliases

To create a new document using an alias, you can write:

const newUser = new User({
  firstName: 'John'
});
await newUser.save();

// When querying, use the Mongoose schema alias, not the database key
const foundUser = await User.findOne({ firstName: 'John' });
console.log(foundUser);

Advanced Aliases Concepts

Aliasing subdocument fields and handling array types can be more complex but follows the same principle:

//...other schema definitions
subDocument: {
  type: new mongoose.Schema({
    subFn: { type: String, alias: 'subFirstName' }
  })
}
//...

To navigate more advanced aspects, you’ll need in-depth knowledge of Mongoose schema types and queries. This can lead to complex associations where awareness of both the actual database fields and their corresponding aliases is crucial.

Conclusion

Through this tutorial, the versatility of field aliases in Mongoose has been highlighted. Using aliases provides an additional layer of abstraction, allowing for more readable code while maintaining descriptive records in MongoDB. As your applications scale, remember to document and manage aliases to ensure a consistent codebase.

Next Article: Using the Mongoose Model.find() function (with examples)

Previous Article: Virtuals in Mongoose: Explained with Examples

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates