Skip to main content

Understanding the Relationship Between Number in Mongoose and double in MongoDB

In Mongoose, a popular ODM (Object Data Modeling) library for MongoDB, using Number as a data type in your schema corresponds to the double type in MongoDB. Let’s explore what this means and how it impacts your data storage and retrieval.

Number in Mongoose and double in MongoDB

1. Mongoose Type: Number

  • In JavaScript/TypeScript, Number is the primary floating-point type.
  • When you specify Number in a Mongoose schema, MongoDB internally stores it as a double, which is a 64-bit floating-point value.
  • This means that when you define a Number field in your Mongoose model, the corresponding MongoDB document will use the double type for that field.

MongoDB Representation:

When a Number field is saved in Mongoose, MongoDB represents it as:

{
"actualCollectionKg": 12.34 // Internally stored as "double" in MongoDB
}

When running queries in MongoDB (e.g., using db.collection.find()), you may see the following representation:

"actualCollectionKg": Number(12.34)

Verifying the Type in MongoDB:

To confirm the data type in MongoDB, you can use the $type operator in your query:

db.collectionOrders.find({ actualCollectionKg: { $type: "double" } })

This query retrieves documents where actualCollectionKg is stored as a double.

Comparison of Supported Numeric Types:

Mongoose TypeMongoDB TypeDescriptionNumberdouble64-bit floating-point valueDecimal128decimalHigh-precision 128-bit decimalCustom Integerint32 or int6432-bit or 64-bit signed integers

When to Use Number vs Decimal128:

  • Use Number if:
  • You are working with general floating-point numbers (e.g., weights, percentages).
  • Precision loss due to floating-point rounding is not critical.
  • Use Decimal128 if:
  • You require high precision for financial data or calculations.
  • You need to avoid rounding errors that can occur with floating-point arithmetic.

Example Mongoose Schema:

Below is an example of a Mongoose schema using Number:

import { Schema, Prop, Document } from '@nestjs/mongoose';

@Schema()
export class CollectionOrder extends Document {
@Prop({ type: Number }) // Mapped to "double" in MongoDB
actualCollectionKg?: number;
}

This schema defines a actualCollectionKg field as a Number, which MongoDB stores as a double.

MongoDB Output Example:

When you save a document using the schema above, the stored MongoDB document might look like this:

{
"_id": "64aefc123456",
"actualCollectionKg": 12.34 // Stored as type: "double"
}

Key Takeaways:

  1. Mongoose’s Number corresponds to MongoDB’s double, a 64-bit floating-point value.
  2. If you need higher precision (e.g., financial data), consider using Decimal128 instead of Number.
  3. Always verify data types when precision is important to ensure the correct type is being used.

By understanding how Mongoose and MongoDB handle numeric types, you can design schemas that suit your application’s needs and avoid common pitfalls related to precision and performance.

Happy coding! ๐Ÿš€

    Popular posts from this blog

    Xcode and iOS Version Mismatch: Troubleshooting "Incompatible Build Number" Errors

    Have you ever encountered a frustrating error while trying to run your iOS app in Xcode, leaving you scratching your head? A common issue arises when your device's iOS version is too new for the Xcode version you're using. This often manifests as an "incompatible build number" error, and looks like this: DVTDeviceOperation: Encountered a build number "" that is incompatible with DVTBuildVersion. This usually happens when you are testing with beta versions of either iOS or Xcode, and can prevent Xcode from properly compiling your storyboards. Let's explore why this occurs and what you can do to resolve it. Why This Error Occurs The core problem lies in the mismatch between the iOS version on your test device and the Software Development Kit (SDK) supported by your Xcode installation. Xcode uses the SDK to understand how to build and run apps for specific iOS versions. When your device runs a newer iOS version than Xcode anticipates, Xcode mi...

    How to Fix the “Invariant Violation: TurboModuleRegistry.getEnforcing(…): ‘RNCWebView’ Could Not Be Found” Error in React Native

    When working with React Native, especially when integrating additional libraries like react-native-signature-canvas , encountering errors can be frustrating. One such error is: Invariant Violation: TurboModuleRegistry. getEnforcing (...): 'RNCWebView' could not be found This error often occurs when the necessary dependencies for a module are not properly linked or when the environment you’re using doesn’t support the required native modules. Here’s a breakdown of how I encountered and resolved this issue. The Problem I was working on a React Native project where I needed to add the react-native-signature-canvas library to capture user signatures. The installation process seemed straightforward: Installed the package: npm install react-native-signature- canvas 2. Since react-native-signature-canvas depends on react-native-webview , I also installed the WebView package: npm install react- native -webview 3. I navigated to the iOS directory and ran: cd ios pod install Everythi...

    Fixing FirebaseMessagingError: Requested entity was not found.

    If you’re working with Firebase Cloud Messaging (FCM) and encounter the error: FirebaseMessagingError: Requested entity was not found. with the error code: messaging/registration-token-not-registered this means that the FCM registration token is invalid, expired, or unregistered . This issue can prevent push notifications from being delivered to users. ๐Ÿ” Possible Causes & Solutions 1️⃣ Invalid or Expired FCM Token FCM tokens are not permanent and may expire over time. If you’re storing tokens in your database, some might be outdated. ✅ Solution: Remove invalid tokens from your database when sending push notifications. Refresh and store the latest FCM token when the app starts. Example: Automatically Refresh Token firebase. messaging (). onTokenRefresh ( ( newToken ) => { // Send newToken to your backend and update the stored token }); 2️⃣ Token Unregistered on Client Device A token might become unregistered if: The app is uninstalled on the user’s device. ...