Schema Data Types In Mongoose


Mongoose is a library that helps you use MongoDB with Node.js.
It makes it easy to create and manage data by using schemas (rules that describe the structure of your data).
Basic Schema Data Types
Here are the most commonly used ones:
String: Represents text data.
const userSchema = new mongoose.Schema({
name: String,
});
Number: Represents numerical data, including integers and floating-point numbers.
const productSchema = new mongoose.Schema({
name: Number,
});
Double: is a data type that allows you to store decimal numbers with high precision.
const temperatureSchema = new Schema({
celsius: Double
});
BigInt : BigInt in Mongoose means handling very large integers using Long
or String
, since the default Number
isn’t always enough.
const questionSchema = new Schema({
answer: BigInt
});
Date: Represents date and time data.
const eventSchema = new mongoose.Schema({
name: Date,
});
Buffer: Represents binary data.
const fileSchema = new mongoose.Schema({
data: Buffer,
});
Boolean: Represents a boolean value (true
or false
).
const userSchema = new mongoose.Schema({
isActive: Boolean,
});
ObjectId: Represents a MongoDB ObjectId, used for referencing other documents.
const postSchema = new mongoose.Schema({
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
});
Array: Represents an array of items. The type of items in the array can also be specified.
const userSchema = new mongoose.Schema({
roles: [String],
});
Mixed: Represents a mixed schema type, allowing any data type. This is generally used when you need to store arbitrary data.
const anySchema = new mongoose.Schema({
arbitraryData: mongoose.Schema.Types.Mixed,
});
Advanced Schema Data Types
Besides simple data types (like string, number, or date), Mongoose also provides advanced schema types.
These are used when you need to store and work with more complex data structures.
👉 In short: Mongoose can handle both simple and complex types of data.
Subdocuments: Define schemas within schemas to represent nested documents.
const addressSchema = new mongoose.Schema({
street: String,
city: String,
zipcode: String,
});
const userSchema = new mongoose.Schema({
name: String,
address: addressSchema,
});
Maps: Represents a map of key-value pairs where keys are strings and values can be of any type.
const schema = new mongoose.Schema({
socialMediaHandles: {
type: Map,
of: String,
},
});
Decimal128: Represents high-precision decimal numbers.
const priceSchema = new mongoose.Schema({
amount: mongoose.Schema.Types.Decimal128,
});
UUID: Represents UUIDs (Universally Unique Identifiers).
const schema = new mongoose.Schema({
uuid: {
type: mongoose.Schema.Types.UUID,
default: () => uuidv4(), // Requires the 'uuid' package
},
});
Benefits of Using Schema Data Types in Mongoose
Data Validation: Mongoose schemas enforce data types for each field in a document, ensuring that the data stored in the database adheres to the defined structure. This helps prevent errors and inconsistencies.
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
createdAt: Date
});
Default Values: Schema data types can be defined with default values, which are used if a document is created without specifying those fields. This simplifies data entry and ensures that required fields are populated with sensible defaults.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, default: 18 },
email: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
Custom Validators: Mongoose allows custom validation functions for schema data types to enforce more complex validation rules beyond simple type checking.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: {
type: Number,
min: [0, 'Age must be positive'],
max: [120, 'Age must be less than 120']
},
email: {
type: String,
validate: {
validator: function(v) {
return /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(v);
},
message: props => `${props.value} is not a valid email!`
},
required: [true, 'User email required']
}
});
Enum Validation: For fields that should only take a specific set of values, Mongoose schemas can define enums to restrict the allowed values.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
role: {
type: String,
enum: ['user', 'admin', 'moderator'],
default: 'user'
}
});
Nested Documents: Mongoose schemas support nested documents and arrays, allowing complex data structures to be stored and validated.
const addressSchema = new mongoose.Schema({
street: String,
city: String,
state: String,
zip: String
});
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
email: { type: String, required: true },
address: addressSchema
});
Indexes: Mongoose allows indexes to be defined in schemas to improve query performance. Indexes can be single-field or compound and can be unique.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
});
userSchema.index({ name: 1, email: -1 });
Virtuals:Virtuals are properties that are not stored in MongoDB but can be defined on the schema and computed dynamically.
userSchema.virtual('fullName').get(function() {
return this.firstName + ' ' + this.lastName;
});
const User = mongoose.model('User', userSchema);
Example of Using Schema Data Types
const mongoose = require('mongoose');
const { Schema } = mongoose;
// Define a schema with various data types
const blogPostSchema = new Schema({
title: { type: String, required: true },
content: String,
author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
tags: [String],
meta: {
votes: Number,
favs: Number,
},
createdAt: { type: Date, default: Date.now },
updatedAt: Date,
isPublished: { type: Boolean, default: false },
views: { type: Map, of: Number },
});
// Create a model
const BlogPost = mongoose.model('BlogPost', blogPostSchema);
// Usage example
const newPost = new BlogPost({
title: 'Understanding Schema Data Types in Mongoose',
content: 'This is a detailed guide on schema data types in Mongoose...',
author: '60d9f7cbb50uud089b7m5h98b42494c9b5f0', // Example ObjectId
tags: ['Mongoose', 'MongoDB', 'Node.js'],
meta: { votes: 10, favs: 5 },
views: { '2024-06-01': 100, '2024-06-02': 150 },
});
newPost.save()
.then(post => console.log('Post saved successfully:', post))
.catch(err => console.error('Error saving post:', err));
Conclusion:
Understanding and using schema data types in Mongoose is very important for working with MongoDB.
They help developers:
keep data accurate,
check that data is valid, and
manage even complex data easily.
Because of these features, Mongoose is a very useful tool for building strong and scalable Node.js apps with MongoDB
Subscribe to my newsletter
Read articles from sumit Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
