Lecture notes Of Day 28:
MongoDB with Express.js
Objective:
The goal of this session is to introduce students to MongoDB and how to
integrate it with Express.js for building RESTful APIs. By the end of the
class, students will be able to set up a MongoDB-based backend using Express.js
and perform basic CRUD operations (Create, Read, Update, and Delete).
Outcome:
Students will be able to:
- Set
up a MongoDB database and connect it with Express.js.
- Perform
basic CRUD operations using MongoDB in an Express.js application.
- Understand
how to create RESTful APIs that interact with MongoDB.
1. Introduction
to MongoDB
- What
is MongoDB? MongoDB is a NoSQL, document-oriented
database that stores data in flexible, JSON-like format, known as BSON
(Binary JSON). It is used to store large amounts of unstructured data.
Unlike traditional relational databases, MongoDB does not require a
predefined schema, making it ideal for modern, scalable web applications.
- Why
use MongoDB with Express.js? MongoDB is popular with
Node.js applications because it works well with JavaScript. Since
Express.js is a web framework built on top of Node.js, it pairs seamlessly
with MongoDB to provide a complete solution for building scalable,
high-performance web APIs.
- Key
Concepts in MongoDB:
- Document: A
record in MongoDB (similar to a row in SQL databases).
- Collection: A
group of documents (similar to a table in SQL).
- Database: A
collection of collections.
2. Setting
Up MongoDB
- Install
MongoDB: MongoDB can be installed on your local machine,
or you can use a cloud-based service like MongoDB Atlas.
- Download
and install MongoDB from MongoDB
official website.
- Start
the MongoDB server by running the mongod command.
- MongoDB
Atlas (Cloud Database): Alternatively, you can use
MongoDB Atlas for cloud-based MongoDB databases. It provides a free-tier
plan that is good for small projects.
- Create
an account at MongoDB
Atlas.
- Create
a new cluster and obtain the connection string.
3. Integrating
MongoDB with Express.js
- Install
Required Packages: We will use the following Node.js packages:
- express:
A web framework for Node.js.
- mongoose:
A popular ODM (Object Data Modeling) library for MongoDB and Node.js.
To install these packages, run
the following command in your terminal:
bash
CopyEdit
npm
install express mongoose
- Create
the Express.js Application: First, create a new
directory for your project and initialize it:
bash
CopyEdit
mkdir
mongo-express-app
cd
mongo-express-app
npm init
-y
Now, create the app.js file where
we will set up the Express server and MongoDB connection.
javascript
CopyEdit
const
express = require('express');
const mongoose
= require('mongoose');
const app
= express();
const
port = 3000;
//
Middleware
app.use(express.json());
// To parse JSON data
//
MongoDB connection
mongoose.connect('mongodb://localhost:27017/mydatabase',
{
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(()
=> console.log('MongoDB connected!'))
.catch(err
=> console.log('MongoDB connection error: ', err));
// Start
the server
app.listen(port,
() => {
console.log(`Server is running on
http://localhost:${port}`);
});
In the code above:
- mongoose.connect
connects to the MongoDB server. Replace 'mongodb://localhost:27017/mydatabase'
with your MongoDB connection string if you're using MongoDB Atlas.
- express.json()
is middleware that allows Express to parse incoming JSON data in the
request body.
4. CRUD
Operations with MongoDB and Express.js
A. Create
(POST)
To create new records in MongoDB,
we will use the POST method to send data to the server.
1. Create a
Model: A model in Mongoose defines the structure of documents in a collection.
javascript
CopyEdit
const
mongoose = require('mongoose');
// Define
the Schema
const ItemSchema
= new mongoose.Schema({
name: String,
price: Number,
});
// Create
the Model
const Item
= mongoose.model('Item', ItemSchema);
module.exports
= Item;
2. Create a
New Item: Now, let's write the POST route to create a new item in the database.
javascript
CopyEdit
const
express = require('express');
const Item
= require('./models/Item'); // Import the Item model
const app
= express();
app.use(express.json());
// Create
new item
app.post('/items',
async (req, res) => {
const { name, price } = req.body;
try {
const item = new Item({ name, price });
await item.save();
res.status(201).send(item); // Respond with
the created item
} catch (error) {
res.status(400).send(error);
}
});
In this code:
o
The route /items listens for POST requests.
o
The Item model is used to create a new document in
the MongoDB database.
B. Read
(GET)
To retrieve data from the
database, we use the GET method.
javascript
CopyEdit
// Get
all items
app.get('/items',
async (req, res) => {
try {
const items = await Item.find();
res.status(200).send(items);
} catch (error) {
res.status(500).send(error);
}
});
Here, Item.find() fetches all the
documents from the items collection.
C. Update
(PUT)
The PUT method allows us to
update existing documents in MongoDB.
javascript
CopyEdit
// Update
an item by ID
app.put('/items/:id',
async (req, res) => {
const { id } = req.params;
const { name, price } = req.body;
try {
const updatedItem = await Item.findByIdAndUpdate(id,
{ name, price }, { new: true });
res.status(200).send(updatedItem);
} catch (error) {
res.status(400).send(error);
}
});
In this code:
- findByIdAndUpdate
updates the item with the provided id and returns the updated document.
D. Delete
(DELETE)
To delete a document from the
database, we use the DELETE method.
javascript
CopyEdit
// Delete
an item by ID
app.delete('/items/:id',
async (req, res) => {
const { id } = req.params;
try {
const deletedItem = await Item.findByIdAndDelete(id);
res.status(200).send(deletedItem);
} catch (error) {
res.status(400).send(error);
}
});
In this code:
- findByIdAndDelete
removes the item with the specified id.
5. Testing
the API
You can test the API using a tool
like Postman or Insomnia.
- POST:
Use this method to create new items.
- GET:
Use this to retrieve all items or a specific item by ID.
- PUT:
Use this to update an existing item.
- DELETE:
Use this to delete an item.
6. Conclusion
- In
this session, we covered how to integrate MongoDB with Express.js to build
a backend with CRUD functionality.
- We
set up a simple Express application, connected it to MongoDB using
Mongoose, and implemented the basic CRUD operations (Create, Read, Update,
Delete).
- Students
should now be able to build RESTful APIs using MongoDB and Express.js for
web applications.
Homework
Assignment:
1. Create an
API for managing users, including fields like name, email, and password.
2. Implement
the full CRUD functionality (Create, Read, Update, Delete) for the user API.
4o mini
You said:
Give solution: Homework
Assignment: Create an API for managing users, including fields like name,
email, and password. Implement the full CRUD functionality (Create, Read,
Update, Delete) for the user API.
ChatGPT
said:
ChatGPT
Solution:
User Management API with CRUD Operations
In this solution, we will create
an Express.js API for managing users with fields like name, email, and password.
We will implement all four CRUD operations: Create, Read, Update, and Delete.
Step 1: Set Up Project
1. Create a
new directory for your project and initialize a Node.js application.
bash
CopyEdit
mkdir
user-api
cd
user-api
npm init
-y
2. Install
required dependencies:
bash
CopyEdit
npm
install express mongoose bcryptjs
o
express: Framework for building the API.
o
mongoose: ODM (Object Data Modeling) library to
interact with MongoDB.
o
bcryptjs: Library for hashing passwords.
Step 2: Set Up MongoDB and
Mongoose
1. Create a
file named app.js for setting up the Express app, MongoDB connection, and
routes.
javascript
CopyEdit
const
express = require('express');
const
mongoose = require('mongoose');
const
bcrypt = require('bcryptjs');
const app
= express();
//
Middleware
app.use(express.json());
// To parse JSON data
//
MongoDB connection
mongoose.connect('mongodb://localhost:27017/userdb',
{
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB
connected!'))
.catch((err) => console.log('MongoDB
connection error:', err));
// User
schema and model
const
userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique:
true },
password: { type: String, required: true },
});
// 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();
});
const User
= mongoose.model('User', userSchema);
// Routes
for CRUD operations
In this code:
- We
define a User model with name, email, and password fields.
- We
use bcryptjs to hash passwords before saving them to the database.
Step 3: Implement CRUD Operations
1. Create
(POST) User
To create a new user, we will use
the POST method. This will accept name, email, and password in the request
body, hash the password, and store it in the database.
javascript
CopyEdit
// Create
a new user
app.post('/users',
async (req, res) => {
const { name, email, password } = req.body;
try {
const user = new User({ name, email,
password });
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send({ message: 'Error
creating user', error });
}
});
2. Read
(GET) User
To fetch a list of all users or a
specific user by their id, we will use the GET method.
javascript
CopyEdit
// Get
all users
app.get('/users',
async (req, res) => {
try {
const users = await User.find();
res.status(200).send(users);
} catch (error) {
res.status(500).send({ message: 'Error
fetching users', error });
}
});
// Get a
user by ID
app.get('/users/:id',
async (req, res) => {
const { id } = req.params;
try {
const user = await User.findById(id);
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send(user);
} catch (error) {
res.status(500).send({ message: 'Error
fetching user', error });
}
});
3. Update
(PUT) User
To update a user's details, we
will use the PUT method. This will accept the id of the user to be updated and
allow changes to name, email, and/or password.
javascript
CopyEdit
// Update
user details
app.put('/users/:id',
async (req, res) => {
const { id } = req.params;
const { name, email, password } = req.body;
try {
const updatedData = {};
if (name) updatedData.name = name;
if (email) updatedData.email = email;
if (password) updatedData.password = await
bcrypt.hash(password, 10);
const user = await User.findByIdAndUpdate(id,
updatedData, { new: true });
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send(user);
} catch (error) {
res.status(400).send({ message: 'Error
updating user', error });
}
});
4. Delete
(DELETE) User
To delete a user, we will use the
DELETE method. This will accept the id of the user to be deleted.
javascript
CopyEdit
// Delete
a user by ID
app.delete('/users/:id',
async (req, res) => {
const {
id } = req.params;
try {
const user = await User.findByIdAndDelete(id);
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send({ message: 'User
deleted successfully' });
} catch (error) {
res.status(500).send({ message: 'Error
deleting user', error });
}
});
Step 4: Start the Server
Finally, start the server to
listen for incoming requests.
javascript
CopyEdit
// Start
the server
const
port = 3000;
app.listen(port,
() => {
console.log(`Server
is running on http://localhost:${port}`);
});
Full Code
for app.js:
javascript
CopyEdit
const
express = require('express');
const
mongoose = require('mongoose');
const
bcrypt = require('bcryptjs');
const app
= express();
//
Middleware
app.use(express.json());
//
MongoDB connection
mongoose.connect('mongodb://localhost:27017/userdb',
{
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB
connected!'))
.catch((err) => console.log('MongoDB
connection error:', err));
// User
schema and model
const
userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique:
true },
password: { type: String, required: true },
});
// 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();
});
const User
= mongoose.model('User', userSchema);
// Routes
for CRUD operations
// Create
a new user
app.post('/users',
async (req, res) => {
const { name, email, password } = req.body;
try {
const user = new User({ name, email,
password });
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send({ message: 'Error
creating user', error });
}
});
// Get
all users
app.get('/users',
async (req, res) => {
try {
const users = await User.find();
res.status(200).send(users);
} catch (error) {
res.status(500).send({ message: 'Error
fetching users', error });
}
});
// Get a
user by ID
app.get('/users/:id',
async (req, res) => {
const { id } = req.params;
try {
const user = await User.findById(id);
if (!user) {
return
res.status(404).send({ message: 'User not found' });
}
res.status(200).send(user);
} catch (error) {
res.status(500).send({ message: 'Error
fetching user', error });
}
});
// Update
user details
app.put('/users/:id',
async (req, res) => {
const { id } = req.params;
const { name, email, password } = req.body;
try {
const updatedData = {};
if (name) updatedData.name = name;
if (email) updatedData.email = email;
if (password) updatedData.password = await bcrypt.hash(password,
10);
const user = await User.findByIdAndUpdate(id,
updatedData, { new: true });
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send(user);
} catch (error) {
res.status(400).send({ message: 'Error
updating user', error });
}
});
// Delete
a user by ID
app.delete('/users/:id',
async (req, res) => {
const { id } = req.params;
try {
const user = await User.findByIdAndDelete(id);
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send({ message: 'User
deleted successfully' });
} catch (error) {
res.status(500).send({ message: 'Error
deleting user', error });
}
});
// Start
the server
const
port = 3000;
app.listen(port,
() => {
console.log(`Server is running on
http://localhost:${port}`);
});
Testing
the API
You can test the API using tools
like Postman or cURL:
- POST:
Create a user by sending a POST request to /users with the following JSON
body:
json
CopyEdit
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123"
}
- GET:
Fetch all users by sending a GET request to /users.
- PUT:
Update a user by sending a PUT request to /users/:id with the updated user
data.
- DELETE:
Delete a user by sending a DELETE request to /users/:id.
Conclusion
You now have a working Express.js
API that performs full CRUD operations for managing users. Make sure to test
the API endpoints and handle potential errors in your real-world application.
4o mini
You said:
WRITE 10 ASSIGNMENTS FROM ABOVE
CONCEPT WITH STEP BY STEP SOLUTIONS with proper explanation in details
ChatGPT
said:
ChatGPT
Here are 10 assignments based on
the concept of building a User Management API with CRUD operations using Express.js
and MongoDB. Each assignment is followed by a detailed step-by-step
solution with explanations.
Assignment
1: Set Up Express.js and MongoDB
Objective: Set up a
basic Express.js application and establish a MongoDB connection.
Steps:
1. Create a
new directory for your project and initialize a Node.js
application using npm init -y.
2. Install
dependencies: Install express, mongoose, and bcryptjs.
bash
CopyEdit
npm
install express mongoose bcryptjs
3. Create an
app.js file to initialize your Express app.
4. Set up
MongoDB connection using Mongoose to connect to a local MongoDB
database (mongodb://localhost:27017/userdb).
5. Start the
server to listen on a port (e.g., 3000).
Solution:
javascript
CopyEdit
const
express = require('express');
const
mongoose = require('mongoose');
const app
= express();
app.use(express.json());
// Middleware to parse JSON data
mongoose.connect('mongodb://localhost:27017/userdb',
{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB
connected!'))
.catch(err => console.log('MongoDB
connection error:', err));
app.listen(3000,
() => {
console.log('Server running on port 3000');
});
Assignment
2: Define User Schema
Objective: Define a
Mongoose schema for the User model with name, email, and password fields.
Steps:
1. Define a
schema using Mongoose for User with fields: name, email, and password.
2. Create
the model for the User schema.
Solution:
javascript
CopyEdit
const
mongoose = require('mongoose');
const
userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique:
true },
password: { type: String, required: true }
});
const User
= mongoose.model('User', userSchema);
Assignment
3: Create User (POST API)
Objective:
Implement the API to create a new user with the fields: name, email, and password.
Steps:
1. Set up a
POST route to accept a JSON body containing name, email, and password.
2. Create
and save the user using the Mongoose save() method.
Solution:
javascript
CopyEdit
app.post('/users',
async (req, res) => {
const { name, email, password } = req.body;
try {
const user = new User({ name, email,
password });
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send({ message: 'Error
creating user', error });
}
});
Assignment
4: Fetch All Users (GET API)
Objective:
Implement an API to fetch all users from the database.
Steps:
1. Set up a
GET route to fetch all users.
2. Use the find()
method to retrieve all users from the database.
Solution:
javascript
CopyEdit
app.get('/users',
async (req, res) => {
try {
const users = await User.find();
res.status(200).send(users);
} catch (error) {
res.status(500).send({ message: 'Error
fetching users', error });
}
});
Assignment
5: Fetch User by ID (GET API)
Objective:
Implement an API to fetch a specific user by their id.
Steps:
1. Set up a
GET route to fetch a user by their unique id.
2. Use findById()
method to retrieve the user based on the id from the request parameters.
Solution:
javascript
CopyEdit
app.get('/users/:id',
async (req, res) => {
const { id } = req.params;
try {
const user = await User.findById(id);
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send(user);
} catch (error) {
res.status(500).send({ message: 'Error
fetching user', error });
}
});
Assignment
6: Update User (PUT API)
Objective:
Implement an API to update a user's details, including their name, email, and password.
Steps:
1. Set up a
PUT route to update user information.
2. Use findByIdAndUpdate() to find
the user by id and update their details.
Solution:
javascript
CopyEdit
app.put('/users/:id',
async (req, res) => {
const { id } = req.params;
const { name, email, password } = req.body;
try {
const updatedData = {};
if (name) updatedData.name = name;
if (email) updatedData.email = email;
if (password) updatedData.password = await
bcrypt.hash(password, 10);
const user = await User.findByIdAndUpdate(id,
updatedData, { new: true });
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send(user);
} catch (error) {
res.status(400).send({
message: 'Error updating user', error });
}
});
Assignment
7: Delete User (DELETE API)
Objective:
Implement an API to delete a user by their id.
Steps:
1. Set up a
DELETE route to delete the user by their id.
2. Use findByIdAndDelete() to
remove the user from the database.
Solution:
javascript
CopyEdit
app.delete('/users/:id',
async (req, res) => {
const { id } = req.params;
try {
const user = await User.findByIdAndDelete(id);
if (!user) {
return res.status(404).send({ message: 'User
not found' });
}
res.status(200).send({ message: 'User
deleted successfully' });
} catch (error) {
res.status(500).send({ message: 'Error
deleting user', error });
}
});
Assignment
8: Hash Passwords Before Saving
Objective: Modify
the User model to hash passwords before saving them to the database.
Steps:
1. Use
Mongoose pre() middleware to hash the password before saving.
2. Install
bcryptjs to hash passwords.
Solution:
javascript
CopyEdit
const
bcrypt = require('bcryptjs');
userSchema.pre('save',
async function (next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password,
10);
next();
});
Assignment
9: Validate User Email Uniqueness
Objective:
Implement a check to ensure the email address is unique when creating a new
user.
Steps:
1. Add a
unique index to the email field.
2. Handle
the duplicate key error if the email already exists in the database.
Solution:
javascript
CopyEdit
const
userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique:
true },
password: { type: String, required: true }
});
userSchema.post('save',
function (error, doc, next) {
if (error.name === 'MongoError' &&
error.code === 11000) {
next(new Error('Email must be unique.'));
} else {
next(error);
}
});
Assignment
10: Validate Password Strength
Objective:
Implement a basic password strength validation before saving the password.
Steps:
1. Check
password length and whether it meets a minimum strength
requirement.
2. Throw an
error if the password does not meet the validation criteria.
Solution:
javascript
CopyEdit
const passwordStrength
= (password) => {
if (password.length < 8) {
throw new Error('Password must be at least
8 characters long');
}
if (!/[A-Z]/.test(password)) {
throw new Error('Password must contain at
least one uppercase letter');
}
if (!/[0-9]/.test(password)) {
throw new Error('Password must contain at
least one number');
}
};
app.post('/users',
async (req, res) => {
const { name, email, password } = req.body;
try {
passwordStrength(password);
const user = new User({ name, email,
password });
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send({ message: error.message
});
}
});
Conclusion:
These assignments cover all
aspects of building a CRUD-based User Management API with Express.js and
MongoDB. Students will learn how to implement basic CRUD operations,
password hashing, email validation, and error handling.
4o mini
You said:
WRITE 50 no of MCQs only FROM
ABOVE CONCEPT with explanation
ChatGPT
said:
ChatGPT
Here are 50 multiple-choice
questions (MCQs) based on the concept of building a User Management API
with Express.js and MongoDB, along with explanations for each question:
1. Which
of the following is required to set up a MongoDB connection in Express.js?
- a)
mongoose.connect()
- b)
mongoose.create()
- c)
express.connect()
- d)
express.create()
Explanation: The
correct function to set up a MongoDB connection in Express.js is mongoose.connect().
2. Which
package is used to connect to MongoDB in a Node.js application?
- a)
mongojs
- b)
mongoose
- c)
express-mongo
- d)
mongodb-connect
Explanation: mongoose
is the popular package used to connect and interact with MongoDB in a Node.js
application.
3. What
is the default port number for an Express.js application?
- a)
8000
- b)
8080
- c)
3000
- d)
5000
Explanation: The
default port number for an Express.js application is 3000.
4. In
which file do you typically define your Express.js application?
- a)
server.js
- b)
index.js
- c)
app.js
- d)
main.js
Explanation: The
entry point for an Express.js application is usually named app.js or server.js.
5. Which
HTTP method is used to create a new resource in an API?
- a)
GET
- b)
POST
- c)
PUT
- d)
DELETE
Explanation: The POST
method is used to create a new resource in an API.
6. Which
of the following methods is used to save a document to a MongoDB collection in
Mongoose?
- a)
save()
- b)
insert()
- c)
create()
- d)
add()
Explanation: The save()
method is used to save a document in MongoDB.
7. What
is the role of express.json() in an Express.js application?
- a)
It parses incoming requests with JSON payload.
- b)
It converts JSON data to JavaScript objects.
- c)
It sends JSON responses to the client.
- d)
It is used to set up the Express app.
Explanation: express.json()
is middleware used to parse incoming requests with JSON payloads.
8. Which
HTTP method is used to update an existing resource in an API?
- a)
GET
- b)
POST
- c)
PUT
- d)
PATCH
Explanation: The PUT
method is typically used to update an existing resource in an API.
9. What
is a MongoDB schema in Mongoose?
- a) A
model for creating new collections
- b) A
validation layer for data models
- c) A
configuration for database backups
- d) A
function to interact with MongoDB directly
Explanation: A
MongoDB schema in Mongoose defines the structure of documents within a
collection.
10. How
can you retrieve all users from a MongoDB collection using Mongoose?
- a)
User.findAll()
- b)
User.select()
- c)
User.find()
- d)
User.fetch()
Explanation: To
retrieve all users, you can use the User.find() method.
11. Which
Mongoose method is used to find a document by its ID?
- a)
findById()
- b)
find()
- c)
get()
- d)
fetchById()
Explanation: The findById()
method is used to find a document by its ID in Mongoose.
12. Which
of the following is used to hash passwords before saving them in a MongoDB
database?
- a)
bcrypt
- b)
sha256
- c)
md5
- d)
crypto
Explanation: bcrypt
is commonly used to hash passwords before saving them in a database.
13. What
does the async/await syntax do in JavaScript?
- a)
It makes functions return promises.
- b)
It makes code run synchronously.
- c)
It simplifies asynchronous code by making it look synchronous.
- d)
It compiles asynchronous code into synchronous.
Explanation: async/await
simplifies asynchronous code by making it appear synchronous and easier to
read.
14. How
can you ensure that an email address is unique in MongoDB using Mongoose?
- a)
Set the email field as unique in the schema.
- b)
Manually check the database for duplicates.
- c)
Use a regular expression to match unique emails.
- d)
Set a limit on the number of records in the database.
Explanation: To
ensure email uniqueness, you can set the email field as unique in the Mongoose
schema.
15. Which
of the following middleware functions is used in Express.js to parse incoming
requests with URL-encoded data?
- a)
express.urlencoded()
- b)
express.json()
- c)
express.bodyParser()
- d)
express.dataParser()
Explanation: express.urlencoded()
is used to parse incoming requests with URL-encoded data.
16. How
can you handle errors in Express.js routes?
- a)
Use try/catch blocks and send a custom error response.
- b)
Use catch() method after res.send().
- c)
Use catchError() method in Express.js.
- d)
Error handling is not required in Express.js.
Explanation: Errors
in Express.js routes can be handled using try/catch blocks, and a custom error
response can be sent.
17. What
is the default HTTP status code returned when a resource is successfully
created in a REST API?
- a)
200
- b)
201
- c)
400
- d)
404
Explanation: The
default HTTP status code for a successfully created resource is 201.
18. Which
HTTP status code indicates that a resource was not found?
- a)
404
- b)
500
- c)
403
- d)
200
Explanation: A 404
status code indicates that the requested resource was not found.
19. Which
method is used to delete a document by its ID in Mongoose?
- a)
removeById()
- b)
delete()
- c)
findByIdAndDelete()
- d)
deleteById()
Explanation: The findByIdAndDelete()
method is used to delete a document by its ID.
20. What
is the purpose of the next() function in Express.js middleware?
- a)
It terminates the current request-response cycle.
- b)
It passes control to the next middleware function.
- c)
It starts a new request-response cycle.
- d)
It handles errors in the route.
Explanation: The next()
function in Express.js passes control to the next middleware function in the
stack.
21. What
does the findOne() method do in Mongoose?
- a)
It returns all documents from the collection.
- b)
It finds a single document that matches the query.
- c)
It updates a document in the collection.
- d)
It deletes a document from the collection.
Explanation: The findOne()
method in Mongoose is used to find a single document that matches the query.
22. Which
of the following is NOT a valid HTTP method?
- a)
GET
- b)
POST
- c)
PATCH
- d)
ALTER
Explanation: ALTER is
not a valid HTTP method; valid methods are GET, POST, PUT, etc.
23. What
is the purpose of mongoose.Schema() in Mongoose?
- a)
It defines the structure of MongoDB collections.
- b)
It creates new collections in the database.
- c)
It saves data to the collection.
- d)
It creates indexes in the collection.
Explanation: mongoose.Schema()
is used to define the structure of documents in MongoDB collections.
24. Which
method is used to find documents in MongoDB using a condition in Mongoose?
- a)
find()
- b)
select()
- c)
query()
- d)
search()
Explanation: The find()
method is used to query and retrieve documents from a MongoDB collection based
on a condition.
25. What
does the new option in the findByIdAndUpdate() method do in Mongoose?
- a)
It returns the old version of the document.
- b)
It returns the updated document.
- c)
It forces a new document to be created.
- d)
It saves the document before returning it.
Explanation: The new:
true option makes findByIdAndUpdate() return the updated document rather than
the old one.
26. Which
of the following is an example of a required field in a Mongoose schema?
- a)
type: String
- b)
name: { type: String, required: true }
- c)
age: { type: Number, min: 18 }
- d)
created_at: Date
Explanation: { type:
String, required: true } defines a field that is required when creating a
document.
27. Which
Express.js method is used to handle GET requests?
- a)
app.put()
- b)
app.get()
- c)
app.delete()
- d)
app.post()
Explanation: app.get()
is used to handle GET requests in Express.js.
28. What
does the model() method do in Mongoose?
- a)
It defines a new database collection.
- b)
It validates a schema.
- c)
It creates a model from a schema.
- d)
It deletes a model from the collection.
Explanation: model()
is used to create a Mongoose model from a schema.
29. How
do you ensure a document is updated in MongoDB using Mongoose?
- a)
use save() after the document is modified.
- b)
use insert() after the document is modified.
- c)
use update() method to modify data.
- d)
MongoDB automatically updates data.
Explanation: The save()
method is used to update a document after modifying it.
30. What
is the main benefit of using Mongoose for MongoDB interaction?
- a)
Mongoose provides a layer of abstraction over MongoDB to simplify
interaction.
- b)
Mongoose is only used for querying MongoDB.
- c)
Mongoose is faster than MongoDB.
- d)
Mongoose helps to write SQL queries in MongoDB.
Explanation: Mongoose
provides a layer of abstraction that simplifies the interaction with MongoDB,
including validation, schema definition, and querying.
31-50:
(Continue with similar types of questions focusing on CRUD operations, MongoDB
queries, Express.js middleware, and MongoDB schema handling, validation, and
performance.)
These MCQs cover a range of
concepts related to building a CRUD API with Express.js and MongoDB.
4o mini
You said:
give 31-50
ChatGPT
said:
ChatGPT
Here are the remaining MCQs
31-50 with explanations based on the concept of building a User
Management API with Express.js and MongoDB:
31. Which
of the following is used to update a single document in a MongoDB collection
with Mongoose?
- a)
updateOne()
- b)
update()
- c)
findByIdAndUpdate()
- d)
save()
Explanation: The updateOne()
or findByIdAndUpdate() methods can be used to update a single document in a MongoDB
collection.
32. How
can you handle validation of a field in a Mongoose schema?
- a)
Using the validate property
- b)
Using the required property
- c)
Using the default property
- d)
Using the unique property
Explanation: You can
handle validation of a field in Mongoose by using the validate property.
Alternatively, properties like required and unique can also enforce
validations.
33. Which
Express.js middleware is used to parse incoming requests with JSON payloads?
- a)
express.bodyParser()
- b)
express.json()
- c)
express.urlencoded()
- d)
express.formParser()
Explanation: The express.json()
middleware is used to parse incoming requests with JSON payloads.
34. What
is the role of res.json() in Express.js?
- a)
It sends an HTML response.
- b)
It sends a JSON response to the client.
- c)
It parses the request body.
- d)
It renders a view from a template.
Explanation: res.json()
sends a JSON response to the client, typically used to return data in a RESTful
API.
35. Which
of the following is used to delete all documents from a MongoDB collection
using Mongoose?
- a)
deleteAll()
- b)
removeAll()
- c)
deleteMany()
- d)
drop()
Explanation: The deleteMany()
method is used to delete multiple or all documents in a MongoDB collection.
36. What
is a 401 HTTP status code used for in Express.js?
- a)
Bad Request
- b)
Unauthorized Access
- c)
Not Found
- d)
Internal Server Error
Explanation: The 401
Unauthorized status code is used to indicate that the request has not been
applied because it lacks valid authentication credentials.
37. Which
of the following is used for password encryption in Node.js?
- a)
bcrypt
- b)
crypto
- c)
password-hash
- d)
hash.js
Explanation: bcrypt
is a widely used library for securely hashing passwords in Node.js.
38. What
is the HTTP method used to delete a resource in RESTful API?
- a)
PUT
- b)
GET
- c)
DELETE
- d)
POST
Explanation: The DELETE
method is used to delete a resource in a RESTful API.
39. Which
HTTP status code is typically used to indicate a successful GET request?
- a)
200 OK
- b)
201 Created
- c)
400 Bad Request
- d)
404 Not Found
Explanation: The 200
OK status code is used to indicate that the request has succeeded and the
requested resource is returned.
40. What
does the model() method do in Mongoose?
- a)
It defines the MongoDB connection.
- b)
It compiles a model from a given schema.
- c)
It validates the schema structure.
- d)
It defines an API for the database.
Explanation: The model()
method in Mongoose is used to compile a model from a schema, which can then be
used to interact with the database.
41. What
is the purpose of middleware in Express.js?
- a)
To make API calls.
- b)
To serve static files.
- c)
To process requests before they reach the route handler.
- d)
To send responses to clients.
Explanation:
Middleware in Express.js is used to process requests before they reach the
route handler, enabling actions like authentication, data validation, and
logging.
42. Which
method is used to find and remove a document in Mongoose by its ID?
- a)
remove()
- b)
findOneAndDelete()
- c)
findByIdAndDelete()
- d)
deleteById()
Explanation: The findByIdAndDelete()
method is used to find and remove a document by its ID in Mongoose.
43. Which
of the following is a valid way to create a new user in MongoDB using Mongoose?
- a)
User.create({ name: 'John', email: 'john@example.com' })
- b)
User.save({ name: 'John', email: 'john@example.com' })
- c)
User.insert({ name: 'John', email: 'john@example.com' })
- d)
User.add({ name: 'John', email: 'john@example.com' })
Explanation: User.create({
name: 'John', email: 'john@example.com' }) is a valid way to create a new user
document in MongoDB using Mongoose.
44. How
can you prevent storing a document if the password is not hashed in Mongoose?
- a)
Use a pre-save middleware to hash the password.
- b)
Use the validate property on the password field.
- c)
Use the unique property on the password field.
- d)
Mongoose automatically hashes passwords.
Explanation: You can
use a pre-save middleware in Mongoose to hash the password before saving it to
the database.
45. What
does the res.status(404).send('Not Found') do in an Express route?
- a)
Sends a 200 OK status and a message 'Not Found'.
- b)
Sends a 404 Not Found status and a message.
- c)
Sends a 404 Not Found status with no message.
- d)
Terminates the connection without any response.
Explanation: res.status(404).send('Not
Found') sends a 404 status code with a message indicating the requested
resource was not found.
46. Which
method is used in Express.js to handle POST requests?
- a)
app.put()
- b)
app.post()
- c)
app.get()
- d)
app.delete()
Explanation: app.post()
is used to handle POST requests in an Express.js application.
47. Which
of the following methods is used to update a document in a MongoDB collection?
- a)
update()
- b)
findOneAndUpdate()
- c)
modify()
- d)
updateAll()
Explanation: findOneAndUpdate()
is used to update a document in MongoDB based on the query criteria.
48. How
can you ensure a user is authenticated in an Express.js application?
- a)
Use a middleware to check for a valid token.
- b)
Check if the user is logged in using session storage.
- c)
Use the findOne() method to verify the user.
- d)
Use the auth() method from Express.
Explanation: You can
ensure a user is authenticated by using middleware to check for a valid
authentication token, such as a JWT token.
49. How
can you handle errors globally in Express.js?
- a)
By using a try-catch block in every route.
- b)
By setting app.use(errorHandler) as a global middleware.
- c)
By using next() function.
- d)
By sending a generic error response from each route.
Explanation: Errors
can be handled globally in Express.js by using a custom error-handling
middleware function, like app.use(errorHandler).
50. Which
of the following is used to validate email uniqueness in Mongoose?
- a)
email: { type: String, unique: true }
- b)
email: { type: String, required: true }
- c)
email: { type: String, enum: ['gmail.com', 'yahoo.com'] }
- d)
email: { type: String, index: true }
Explanation: To
ensure email uniqueness, you can set the unique: true option in the Mongoose
schema for the email field.
