In Mongoose, nested objects are implemented by defining the structure of another object within a Schema. This can be achieved by either directly defining the object's fields within the parent Schema or by creating a separate Schema and embedding it as a subdocument within the parent Schema. Below, I will illustrate how to nest objects in Mongoose using two methods.
Method 1: Defining Objects Directly within the Parent Schema
This method involves directly defining an object structure within the parent Schema. This approach is suitable for simpler nested structures where the nested objects do not need to be reused.
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ name: String, age: Number, address: { street: String, city: String, zipCode: Number } }); const User = mongoose.model('User', userSchema); // Create a new user with the model const newUser = new User({ name: '张三', age: 30, address: { street: '中山路', city: '北京', zipCode: 100000 } }); newUser.save() .then(doc => console.log('New user saved successfully:', doc)) .catch(err => console.error('Error saving:', err));
Method 2: Using a Subschema
If the nested objects are more complex or need to be reused in multiple places, you can create a separate Schema and reference it within the parent Schema. This improves code maintainability and reusability.
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; // Create a separate Schema for address const addressSchema = new Schema({ street: String, city: String, zipCode: Number }); // Reference the address Schema within the user Schema const userSchema = new Schema({ name: String, age: Number, address: addressSchema }); const User = mongoose.model('User', userSchema); // Create a new user with the model const newUser = new User({ name: '李四', age: 25, address: { street: '长安街', city: '上海', zipCode: 200000 } }); newUser.save() .then(doc => console.log('New user saved successfully:', doc)) .catch(err => console.error('Error saving:', err));
By using the above two methods, you can implement nested objects in Mongoose. The choice of method depends on specific requirements, such as the complexity of the nested objects and whether the structure needs to be reused across multiple models.