What is Mongoose and how does it relate to MongoDB?
Answer
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution to model your application data, with built-in type casting, validation, query building, and business logic hooks. MongoDB is a schemaless NoSQL database — documents within the same collection can have different structures. Mongoose adds a schema layer on top, enforcing structure and types. Key concepts: (1) Schema: defines document structure, types, validation, defaults: const userSchema = new Schema({ name: String, email: { type: String, required: true, unique: true } });; (2) Model: a class compiled from the schema for querying: const User = mongoose.model("User", userSchema);; (3) CRUD: User.create(), User.find(), User.findById(), User.findByIdAndUpdate(), User.deleteOne(); (4) Middleware (hooks): pre/post save, pre/post find — useful for hashing passwords or logging; (5) Population: populate() for joining documents across collections.
Previous
What is bcrypt and why is it used for passwords?
Next
What is connection pooling in Node.js database access?