Facebook Pixel

Node.js MongoDB and Mongoose Interview Questions Schemas, Indexes, and Aggregation

Master MongoDB and Mongoose interview questions for Node.js schemas, indexes, aggregation, ref/populate, and performance optimization.

Node.js MongoDB and Mongoose Interview Questions

MongoDB and Mongoose are the most common database stack for Node.js. Here are interview questions.

Q1: What Is the Difference Between MongoDB and Mongoose?

Answer:

  • MongoDB NoSQL database that stores JSON-like documents
  • Mongoose ODM (Object Data Modeling) library for MongoDB in Node.js

Mongoose adds:

  • Schema definition and validation
  • Type casting
  • Middleware (pre/post hooks)
  • Population (ref)
  • Query building

Q2: What Is a Mongoose Schema vs Model?

Answer:

// Schema Defines the structure const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, unique: true }, age: { type: Number, min: 18 } }); // Model Constructor for creating documents const User = mongoose.model("User", userSchema); // Create a document const user = new User({ name: "John", email: "[email protected]", age: 25 }); await user.save();

Q3: What Are Indexes and Why Are They Important?

Answer: Indexes improve query performance by creating a sorted data structure.

// Single field index userSchema.index({ email: 1 }); // Compound index connectionRequestSchema.index({ fromUserId: 1, toUserId: 1 }, { unique: true }); // Text index (for search) postSchema.index({ content: "text" });

Without indexes, MongoDB scans every document (collection scan). With indexes, MongoDB uses the index to find documents quickly (index scan).

Q4: What Is ref and populate in Mongoose?

Answer:

// Schema with ref const postSchema = new mongoose.Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: "User" } }); // Populate replaces ObjectId with the actual document const posts = await Post.find().populate("author", "name email"); // Returns posts with full author objects instead of just ObjectIds

Q5: What Is MongoDB Aggregation?

Answer: Aggregation processes data through a pipeline of stages:

const stats = await Order.aggregate([ { $match: { status: "completed" } }, // Filter { $group: { _id: "$userId", total: { $sum: "$amount" } } }, // Group { $sort: { total: -1 } }, // Sort { $limit: 10 } // Limit ]); // Returns top 10 users by total order amount

Common stages: $match, $group, $sort, $limit, $skip, $lookup (join), $unwind, $project.

Q6: What Is the Difference Between .find() and .findOne()?

Answer:

// find() Returns an array (even if 0 or 1 result) const users = await User.find({ age: 25 }); // findOne() Returns a single document (or null) const user = await User.findOne({ email: "[email protected]" });

Q7: How Do You Handle Mongoose Errors?

Answer:

// Validation error try { await User.create({ name: "" }); // Fails required validation } catch (err) { if (err.name === "ValidationError") { const messages = Object.values(err.errors).map(e => e.message); // ["Path name is required."] } // Duplicate key error if (err.code === 11000) { const field = Object.keys(err.keyPattern)[0]; // "Duplicate email" } // Cast error (invalid ObjectId) if (err.name === "CastError") { // "Invalid userId" } }

Q8: What Are Mongoose Middleware (Hooks)?

Answer:

// Pre-save hook (hash password before saving) userSchema.pre("save", async function(next) { if (!this.isModified("password")) return next(); this.password = await bcrypt.hash(this.password, 10); next(); }); // Post-save hook (send welcome email after saving) userSchema.post("save", function(doc) { sendWelcomeEmail(doc.email); });

The Takeaway

MongoDB/Mongoose interview questions cover: MongoDB vs Mongoose (database vs ODM with schemas and validation), schema vs model (structure vs constructor), indexes (single, compound, unique, text speed up queries), ref and populate (replace ObjectIds with documents), aggregation pipeline ($match, $group, $sort, $lookup), find vs findOne (array vs single), error handling (validation, duplicate key, cast), and middleware hooks (pre/post save for hashing and emails).

MongoDB is a NoSQL database that stores JSON-like documents. Mongoose is an ODM (Object Data Modeling) library for MongoDB in Node.js that adds schema definition, validation, type casting, middleware hooks, population (ref), and query building.

Indexes create a sorted data structure that speeds up queries. Without indexes, MongoDB scans every document (collection scan). With indexes, MongoDB uses the index (index scan). Types: single field, compound (multiple fields), unique (no duplicates), and text (for search).

ref is a schema option that references documents in another collection (stores ObjectId). populate replaces the ObjectId with the actual document when querying: Post.find().populate('author', 'name email'). This is like a JOIN in SQL.

Aggregation processes data through a pipeline of stages: $match (filter), $group (group and aggregate like sum/avg), $sort, $limit, $skip, $lookup (join collections), $unwind (deconstruct arrays), $project (select fields). Used for analytics and complex data processing.

Pre and post hooks that run before/after document operations. pre('save') is commonly used for password hashing. post('save') for sending emails. pre('find') for query modification. pre('remove') for cleanup. They let you add behavior without modifying the main logic.

Ready to master Node.js completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.