Q1. What is a Mongoose schema?
A schema defines the structure of documents within a collection, including field names, data types, default values, validations, and options. Example:
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, min: 0 },
email: { type: String, unique: true },
createdAt: { type: Date, default: Date.now }
});
Q2. What are schema types in Mongoose?
Common schema types: String, Number, Date, Boolean, Buffer, ObjectId, Array, Map, Mixed, Decimal128. You can also nest schemas:
address: {
street: String,
city: String,
zip: Number
}
Q3. How do you define indexes in Mongoose schemas?
Indexes can be defined in the schema:
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ age: -1, name: 1 });
Or as schema options: new mongoose.Schema({...}, { autoIndex: true });
Q4. What is the difference between schema and model?
A schema defines the structure, validation, and middleware. A model is a compiled version of the schema that provides an interface to interact with a specific collection. You create a model from a schema:
const User = mongoose.model('User', userSchema);
The model's name determines the collection name (pluralized, lowercase).Q5. How do you use virtual properties in Mongoose?
Virtuals are document properties that are not stored in MongoDB. They are computed from other fields:
userSchema.virtual('fullName').get(function() {
return this.firstName + ' ' + this.lastName;
});
To include virtuals in JSON/output, set toJSON: { virtuals: true }.