How do you connect Express.js to MongoDB using Mongoose?
Answer
Install Mongoose: npm install mongoose. Connect in your app entry point: mongoose.connect(process.env.MONGODB_URI). Define a Schema and Model: const userSchema = new mongoose.Schema({ name: String, email: { type: String, unique: true } }); const User = mongoose.model('User', userSchema);. Use in route handlers: const users = await User.find(); const user = await User.findById(req.params.id);. Mongoose adds validation, virtuals, middleware hooks (pre/post save), and query building on top of the native MongoDB driver. Store the connection string in .env and never commit it. Handle connection errors and use connection pooling (Mongoose manages this automatically).
Previous
What is input validation and how do you do it in Express?
Next
What is async/await error handling in Express.js?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?