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 adouble
, 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 thedouble
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 TypeDescriptionNumberdouble
64-bit floating-point valueDecimal128decimal
High-precision 128-bit decimalCustom Integerint32
or int64
32-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:
- Mongoose’s
Number
corresponds to MongoDB’sdouble
, a 64-bit floating-point value. - If you need higher precision (e.g., financial data), consider using
Decimal128
instead ofNumber
. - 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! ๐