Sling Academy
Home/Node.js/Mongoose: How to use singular name for collection

Mongoose: How to use singular name for collection

Last updated: December 31, 2023

Introduction

In MongoDB, collections typically have plural names, but sometimes a singular name aligns better with project conventions. This tutorial dissects Mongoose methods for defining a singular collection name for MongoDB through code examples, showcasing methods from basic to advanced while employing the latest Node.js and JavaScript/TypeScript syntax.

Understanding Mongoose Schemas

To begin using singular collection names, we must first understand the connection between Mongoose schemas and collection naming conventions.

import mongoose from 'mongoose';

const { Schema } = mongoose;

const kittySchema = new Schema({
  name: String
});

Default Collection Naming

Mongoose by default pluralizes the model name to determine the collection name.

mongoose.model('Kitty', kittySchema); // Uses the 'kitties' collection

Overriding Default Behavior

To use a singular name, you can specify the collection name in the schema’s third argument.

const kittySchema = new Schema({
  name: String
}, { collection: 'kitty' });
mongoose.model('Kitty', kittySchema); // Uses the 'kitty' collection

Advanced Collection Naming

Let’s dive deeper into customizing collection names with more advanced patterns and use cases.

Dynamic Collection Naming

For varying collection names at runtime, a function returning a collection name can be utilized.

const kittySchema = new Schema({
  name: String,
  typeId: Number
}, {
  collection: function() {
    return `kitty_${this.typeId}`;
  }
});

Integration with TypeScript

When using TypeScript, define your schema with strongly typed interfaces.

import mongoose, { Document, Schema } from 'mongoose';

interface IKitty extends Document {
  name: string;
}

const kittySchema = new Schema({...
}, { collection: 'kitty' });

Best Practices

Incorporating best practices ensures consistency and maintainability in your projects. Here’s how to uphold high standards while using singular collection names.

Consistent Naming Conventions

Choose a naming convention that is consistent across your project and document the decision for your team.

// Bad: inconsistent naming
mongoose.model('blogPost', blogPostSchema); // 'blogposts'
mongoose.model('User', userSchema, 'user');
// Good: consistency
mongoose.model('BlogPost', blogPostSchema, 'blogPost');
mongoose.model('User', userSchema, 'user');

Documenting Schema Design

Be descriptive with your schema designs and include comments for clarity when defining collection names.

const userSchema = new Schema({...
}, {
  // Explicitly defining a singular collection name
  collection: 'user' 
});

Handling Potential Pitfalls

Common errors and challenges might emerge when working with custom collection names.

Error Handling

Handle potential errors gracefully such as those arising from non-existent collections or misnaming.

try {
  // Attempt to use the custom collection
  mongoose.model('Kitty', kittySchema);
} catch (error) {
  console.error('Error with custom collection name:', error);
}

Querying Custom Collections

When querying, ensure to reference the collection by the custom name you’ve set.

const Kitty = mongoose.model('Kitty');

Kitty.find({}).then(kitties => {
  console.log(kitties);
}).catch(error => {
  console.error('Query failed:', error);
});

Summary

This tutorial guided you through utilizing singular collection names in Mongoose. From overruling default pluralization to dynamic and typed schemas, this approach opens the door to cleaner, more controlled, and semantic data structures.

Next Article: Mongoose $match operator (with examples)

Previous Article: Mongoose: How to update values in an array of objects

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