In Mongoose, we can store object data by defining a Schema. Each Schema maps to a MongoDB collection, and each field in the Schema corresponds to an attribute of a document within that collection.
To store an object, you can use a nested object structure or a sub-schema within the Schema. Here are two primary methods for storing object data:
Method 1: Using a Nested Object
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ name: String, address: { street: String, city: String, zipCode: String } }); const User = mongoose.model('User', userSchema);
In this example, we define a model named User with an address field. The address field is an object containing three attributes: street, city, and zipCode.
Method 2: Using a Sub-Schema
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; const addressSchema = new Schema({ street: String, city: String, zipCode: String }); const userSchema = new Schema({ name: String, address: addressSchema }); const User = mongoose.model('User', userSchema);
In this example, we first define an addressSchema, and then incorporate it into the userSchema. This ensures that the address field in each User document is stored according to the addressSchema definition.
One advantage of using a sub-schema is that it enables schema reusability and results in a more organized structure. When the address data is used across multiple locations, this approach is more efficient.
Both approaches—using a nested object or a sub-schema—effectively manage and store structured object data within Mongoose. This results in a clearer data model and simplifies subsequent data operations and maintenance.