Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Mongoose ODM setup
📖 Scenario: You are building a simple Express app that needs to store user data in a MongoDB database. To do this, you will set up Mongoose, a tool that helps you work with MongoDB in a friendly way.
🎯 Goal: Set up Mongoose in your Express app by creating a connection to MongoDB, defining a user schema, and creating a model to interact with the users collection.
📋 What You'll Learn
Create a Mongoose connection to a local MongoDB database named userdb
Define a Mongoose schema called userSchema with fields name (string) and email (string)
Create a Mongoose model called User using the userSchema
Export the User model for use in other parts of the app
💡 Why This Matters
🌍 Real World
Mongoose is widely used in Node.js apps to simplify working with MongoDB databases by providing a clear structure and easy methods to create, read, update, and delete data.
💼 Career
Knowing how to set up Mongoose is essential for backend developers working with Node.js and MongoDB, a common stack in web development jobs.
Progress0 / 4 steps
1
Connect to MongoDB with Mongoose
Write code to import mongoose and connect to a MongoDB database at mongodb://localhost:27017/userdb using mongoose.connect.
Express
Hint
Use require('mongoose') to import Mongoose. Then call mongoose.connect with the MongoDB URL.
2
Define a user schema
Create a constant called userSchema and assign it a new mongoose.Schema with fields name and email, both of type String.
Express
Hint
Use new mongoose.Schema({ name: String, email: String }) to define the schema.
3
Create the User model
Create a constant called User and assign it the result of mongoose.model with the name 'User' and the userSchema.
Express
Hint
Use mongoose.model('User', userSchema) to create the model.
4
Export the User model
Add a line to export the User model using module.exports = User.
Express
Hint
Use module.exports = User to export the model.
Practice
(1/5)
1. What is the main purpose of using mongoose.connect() in an Express app?
easy
A. To connect the Express app to a MongoDB database
B. To start the Express server
C. To define data models for the app
D. To handle HTTP requests
Solution
Step 1: Understand the role of mongoose.connect()
This function is used to establish a connection between the Express app and the MongoDB database.
Step 2: Differentiate from other functions
Starting the server or defining models are separate tasks; mongoose.connect() specifically handles database connection.
Final Answer:
To connect the Express app to a MongoDB database -> Option A
Quick Check:
mongoose.connect() = Connect DB [OK]
Hint: Remember: connect() links app to database [OK]
Common Mistakes:
Confusing connect() with server start
Thinking connect() defines models
Assuming connect() handles HTTP requests
2. Which of the following is the correct syntax to connect Mongoose to a MongoDB database URL stored in dbURI?
easy
A. mongoose.connect = dbURI
B. mongoose.connect(dbURI).then(() => console.log('Connected'))
C. mongoose.connect(dbURI, callback())
D. mongoose.connect(dbURI).catch(console.log('Error'))
Solution
Step 1: Identify correct use of mongoose.connect()
The method returns a promise, so chaining .then() for success is correct.
4. Identify the error in this Mongoose connection code:
mongoose.connect('mongodb://localhost:27017/mydb', () => {
console.log('Connected to DB');
}).catch(err => console.error(err));
medium
A. console.log should be outside connect()
B. The database URL is incorrect
C. Missing await keyword before connect()
D. Using a callback inside connect() with .catch() causes an error
Solution
Step 1: Understand mongoose.connect() usage
It returns a promise; mixing callback and .catch() is incorrect and causes errors.
Step 2: Identify correct pattern
Use either callback or promise, not both together.
Final Answer:
Using a callback inside connect() with .catch() causes an error -> Option D
Quick Check:
Callback and .catch() can't be combined [OK]
Hint: Use either callback or promise, not both [OK]
Common Mistakes:
Mixing callbacks and promises
Assuming .catch() works with callbacks
Ignoring promise nature of connect()
5. You want to connect to MongoDB using Mongoose and log a custom message on success or failure. Which code correctly implements this with async/await inside an Express app?
hard
A. async function connectDB() {
try {
await mongoose.connect(dbURI);
console.log('DB connected');
} catch (err) {
console.error('Connection failed', err);
}
}