Sling Academy
Home/Node.js/Using BigInt Schema Type in Mongoose

Using BigInt Schema Type in Mongoose

Last updated: December 30, 2023

Handling large integers in Mongoose has become straightforward with the BigInt schema type. This article explores its integration and practical usage in Node.js applications.

Before we dive into BigInts, ensure that you have Node.js installed, along with Mongoose, and that you’re familiar with JavaScript’s latest syntax features.

BigInt Basics

The native JavaScript BigInt type allows us to work with integer values that exceed the limits of the Number type. Here’s how to define a BigInt in Mongoose:

const mongoose = require('mongoose');

const mySchema = new mongoose.Schema({
  largeNumber: mongoose.Schema.Types.BigInt
});

Storing Large Numbers

To store values that exceed Number.MAX_SAFE_INTEGER, use a BigInt:

const MyModel = mongoose.model('MyModel', mySchema);

async function saveBigNumber() {
  const largeValue = BigInt('9007199254740993');
  const document = new MyModel({ largeNumber: largeValue });
  await document.save();
  console.log('Saved large number:', largeValue.toString());
}

saveBigNumber();

Querying BigInt Fields

Querying documents with BigInt fields is similar to using regular numbers. Here’s an example:

async function findBigNumber() {
  const result = await MyModel.find({ largeNumber: BigInt('9007199254740993') });
  console.log('Found document:', result);
}

findBigNumber();

Advanced Usage

For handling more complex cases such as aggregation or large numerical operations, Mongoose’s BigInt type can be very powerful:

async function aggregateBigNumbers() {
  const aggregationResult = await MyModel.aggregate([
    {
      $match: {
        largeNumber: { $gt: BigInt('9007199254740992') }
      }
    },
    {
      $group: {
        _id: null,
        maxLargeNumber: { $max: '$largeNumber' }
      }
    }
  ]);
  console.log('Aggregation Result:', aggregationResult);
}

aggregateBigNumbers();

Considerations

Working with BigInts in Mongoose requires careful type casting and understanding of JavaScript’s limitations when it comes to number precision. Always serialize BigInts to strings when sending over a network or logging.

There might be issues related to the dynamic nature of JavaScript’s typing system. Using TypeScript or thorough validation can help mitigate potential problems.

Conclusion

BigInts in Mongoose offer a robust solution for dealing with large integers. With correct implementation and attention to JavaScript’s intricacies, they seamlessly integrate into a Node.js application’s data layer.

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