Lecture Notes Of Class 13: CRUD Operations
with MongoDB and Mongoose
Objective:
The primary objective of this class is to understand how to perform CRUD
(Create, Read, Update, and Delete) operations using MongoDB and Mongoose in a
Node.js application.
1. Introduction to
MongoDB and Mongoose
What is MongoDB?
MongoDB is a NoSQL
database that stores data in a flexible, JSON-like format called BSON (Binary
JSON). Unlike traditional SQL databases, MongoDB is schema-less, meaning you do
not need to define the structure of your documents in advance. This makes it ideal
for modern applications that need flexibility in storing unstructured or
semi-structured data.
What is Mongoose?
Mongoose is an ODM
(Object Data Modeling) library for MongoDB and Node.js. It provides a
higher-level abstraction over MongoDB’s native driver, allowing you to define
schemas for your data, perform validation, and easily manage relationships
between data.
2. Setting up MongoDB
with Node.js
Installing MongoDB and
Mongoose
To begin working with
MongoDB in Node.js, you need to install MongoDB and Mongoose.
1.
Install MongoDB:
o If
you're using a local MongoDB instance, make sure you have MongoDB installed on
your machine.
2.
Install Mongoose:
You can install Mongoose via npm in your Node.js application.
bash
CopyEdit
npm install mongoose
3. Creating a Mongoose
Model and Schema
Mongoose models are
defined by creating a Schema. A Schema is like a blueprint for the data that
you want to store. It defines the structure, types, validation, and other
properties for the documents.
Creating a Mongoose
Schema
Let’s define a simple Student
schema that will have the following fields:
- name
(String)
- age
(Number)
- email
(String)
- created_at
(Date)
Here’s how you can define
the schema and model:
js
CopyEdit
// Import Mongoose
const mongoose = require('mongoose');
// Create a schema for a
student
const studentSchema = new
mongoose.Schema({
name: {
type: String,
required: true, // Name is a required field
},
age: {
type: Number,
required: true, // Age is a required field
},
email: {
type: String,
required: true, // Email is a required field
unique: true, // Email should be unique
},
created_at: {
type: Date,
default: Date.now, // Set default to current date and time
},
});
// Create a model using
the schema
const Student = mongoose.model('Student',
studentSchema);
// Export the model to
use it in other parts of the application
module.exports = Student;
4. CRUD Operations in
MongoDB with Mongoose
Once the model is
defined, you can perform CRUD operations: Create, Read, Update, and Delete.
Create Operation (Insert
Data)
The create() method is
used to add new documents to the MongoDB collection. It accepts an object that
matches the schema.
Example:
js
CopyEdit
const mongoose = require('mongoose');
const Student = require('./models/Student');
// Import the student model
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/studentDB',
{
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Create a new student
document
const newStudent = new Student({
name: 'John Doe',
age: 22,
email: 'john.doe@example.com',
});
// Save the document to
the database
newStudent.save()
.then((student) => {
console.log('Student created:', student);
})
.catch((error) => {
console.error('Error creating student:',
error);
});
Read Operation (Fetch
Data)
The find() method
retrieves documents from the collection. You can provide a filter to search for
specific documents.
Example:
js
CopyEdit
// Fetch all students
Student.find()
.then((students) => {
console.log('All students:', students);
})
.catch((error) => {
console.error('Error fetching students:',
error);
});
// Fetch a specific
student by email
Student.findOne({ email: 'john.doe@example.com'
})
.then((student) => {
console.log('Student found:', student);
})
.catch((error) => {
console.error('Error fetching student:',
error);
});
Update Operation (Modify
Data)
The updateOne() or updateMany()
methods allow you to update existing documents. You specify the condition to
find the document and the data to update.
Example:
js
CopyEdit
// Update a student's age
by their email
Student.updateOne({ email:
'john.doe@example.com' }, { age: 23 })
.then((result) => {
console.log('Student updated:', result);
})
.catch((error) => {
console.error('Error updating student:',
error);
});
Delete Operation (Remove
Data)
The deleteOne() or deleteMany()
methods are used to remove documents from the collection.
Example:
js
CopyEdit
// Delete a student by
email
Student.deleteOne({ email:
'john.doe@example.com' })
.then((result) => {
console.log('Student deleted:', result);
})
.catch((error) => {
console.error('Error deleting student:',
error);
});
5. Handling Errors and
Validation
Mongoose allows you to
define validation rules within the schema. These rules can check for required
fields, data types, and custom validations.
Example of validation:
js
CopyEdit
const studentSchema = new
mongoose.Schema({
name: {
type: String,
required: true, // Name is required
},
age: {
type: Number,
min: [18, 'Age must be at least 18'], //
Age must be at least 18
},
});
If a validation fails,
Mongoose will throw an error, which can be handled using catch().
6. Summary
In this class, you have
learned how to:
1.
Set up MongoDB and Mongoose in a Node.js
application.
2.
Create a Mongoose model and define a
schema for the data.
3.
Perform CRUD operations (Create, Read,
Update, Delete) using Mongoose methods.
4.
Handle validation and errors.
7. Lab Tasks
Task 1: Create a Mongoose
Model and Schema
- Create
a schema for a "Product" or "Employee" model with the
fields of your choice (e.g., name, price, description for a product, or
name, position, department for an employee).
Task 2: Implement CRUD
Operations
- Create
a simple Node.js application where you:
- Add
a new product or employee (Create operation).
- Display
all products or employees (Read operation).
- Update
an existing product or employee (Update operation).
- Delete
a product or employee (Delete operation).
By the end of this class,
students should have a solid understanding of how to interact with MongoDB
using Mongoose and should be able to perform basic CRUD operations within a
Node.js application.
4o mini
You said:
Solution: Task 1: Create
a Mongoose Model and Schema Create a schema for a "Product" or
"Employee" model with the fields of your choice (e.g., name, price,
description for a product, or name, position, department for an employee). Task
2: Implement CRUD Operations Create a simple Node.js application where you: Add
a new product or employee (Create operation). Display all products or employees
(Read operation). Update an existing product or employee (Update operation).
Delete a product or employee (Delete operation).
ChatGPT said:
ChatGPT
Solution: Task 1 &
Task 2
Here’s a step-by-step
solution to implement a basic Node.js application that performs CRUD operations
with a Mongoose model and schema. We will create a Product model and perform
the Create, Read, Update, and Delete operations.
Task 1: Create a Mongoose
Model and Schema
We will create a schema
for a Product model with the following fields:
- name
(String): The name of the product.
- price
(Number): The price of the product.
- description
(String): A short description of the product.
Step 1.1: Setting up the
Project
1.
Initialize a Node.js project.
bash
CopyEdit
npm init -y
2.
Install required dependencies:
bash
CopyEdit
npm install mongoose
express
3.
Create a file named app.js for the Node.js
application.
Step 1.2: Create the
Mongoose Schema for Product
In the app.js file, first
set up the connection to MongoDB and define the Product schema.
js
CopyEdit
const mongoose = require('mongoose');
const express = require('express');
const app = express();
app.use(express.json()); // Middleware to parse JSON requests
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/productDB',
{
useNewUrlParser: true,
useUnifiedTopology:
true,
});
// Define the Product
Schema
const productSchema = new
mongoose.Schema({
name: {
type: String,
required: true, // Name is required
},
price: {
type: Number,
required: true, // Price is required
},
description: {
type: String,
required: true, // Description is required
},
});
// Create the Product
Model
const Product = mongoose.model('Product',
productSchema);
app.listen(3000, () =>
{
console.log('Server is running on port 3000');
});
Task 2: Implement CRUD
Operations
Now, let’s implement the
CRUD operations for the Product model.
Step 2.1: Create
Operation (Add New Product)
Create an endpoint to add
a new product to the database:
js
CopyEdit
// Create a new product
(POST request)
app.post('/products', async
(req, res) => {
const { name, price, description } = req.body;
// Create a new product instance
const product = new Product({
name,
price,
description,
});
try {
// Save the product to the database
const savedProduct = await product.save();
res.status(201).json(savedProduct); // Send the saved product as a response
} catch (err) {
res.status(400).json({ error: err.message
}); // Handle error
}
});
To test the Create
operation, you can use Postman or any HTTP client to send a POST request to http://localhost:3000/products
with the following JSON body:
json
CopyEdit
{
"name": "Laptop",
"price": 1000,
"description": "A high-end
gaming laptop."
}
Step 2.2: Read Operation
(Display All Products)
Create an endpoint to
retrieve all products from the database:
js
CopyEdit
// Get all products (GET
request)
app.get('/products', async
(req, res) => {
try {
// Retrieve all products from the database
const products = await Product.find();
res.status(200).json(products); // Send the products as a response
} catch (err) {
res.status(500).json({ error: err.message
}); // Handle error
}
});
To test the Read
operation, you can visit http://localhost:3000/products using your browser or
an HTTP client to see all the products.
Step 2.3: Update
Operation (Modify Existing Product)
Create an endpoint to
update an existing product:
js
CopyEdit
// Update a product (PUT
request)
app.put('/products/:id', async
(req, res) => {
const { name, price, description } = req.body;
const { id } = req.params;
try {
// Find the product by ID and update its
fields
const updatedProduct = await Product.findByIdAndUpdate(
id,
{ name, price, description },
{ new: true } // Return the updated product
);
if (!updatedProduct) {
return res.status(404).json({ message: 'Product
not found' });
}
res.status(200).json(updatedProduct); // Send the updated product
} catch (err) {
res.status(400).json({ error: err.message
}); // Handle error
}
});
To test the Update
operation, use Postman to send a PUT request to http://localhost:3000/products/:id
where :id is the ID of the product you want to update. Include a JSON body like
this:
json
CopyEdit
{
"name": "Updated Laptop",
"price": 1100,
"description": "An updated
description for the gaming laptop."
}
Step 2.4: Delete
Operation (Remove a Product)
Create an endpoint to
delete a product:
js
CopyEdit
// Delete a product
(DELETE request)
app.delete('/products/:id',
async (req, res) => {
const { id } = req.params;
try {
// Delete the product by ID
const deletedProduct = await Product.findByIdAndDelete(id);
if (!deletedProduct) {
return res.status(404).json({ message: 'Product
not found' });
}
res.status(200).json({ message: 'Product
deleted successfully' });
} catch (err) {
res.status(400).json({ error: err.message
}); // Handle error
}
});
To test the Delete
operation, use Postman to send a DELETE request to http://localhost:3000/products/:id
where :id is the ID of the product you want to delete.
Final App Code
Here is the complete code
for app.js:
js
CopyEdit
const mongoose = require('mongoose');
const express = require('express');
const app = express();
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/productDB',
{
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define the Product
Schema
const productSchema = new
mongoose.Schema({
name: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
description: {
type: String,
required: true,
},
});
// Create the Product
Model
const Product = mongoose.model('Product',
productSchema);
// Create a new product
(POST request)
app.post('/products', async
(req, res) => {
const { name, price, description } = req.body;
const product = new Product({ name, price,
description });
try {
const savedProduct = await product.save();
res.status(201).json(savedProduct);
} catch (err) {
res.status(400).json({ error: err.message
});
}
});
// Get all products (GET
request)
app.get('/products', async
(req, res) => {
try {
const products = await Product.find();
res.status(200).json(products);
} catch (err) {
res.status(500).json({ error: err.message
});
}
});
// Update a product (PUT
request)
app.put('/products/:id', async
(req, res) => {
const { name, price, description } = req.body;
const { id } = req.params;
try {
const updatedProduct = await Product.findByIdAndUpdate(id,
{ name, price, description }, { new: true });
if (!updatedProduct) return res.status(404).json({
message: 'Product not found' });
res.status(200).json(updatedProduct);
} catch (err) {
res.status(400).json({ error: err.message
});
}
});
// Delete a product
(DELETE request)
app.delete('/products/:id',
async (req, res) => {
const { id } = req.params;
try {
const deletedProduct = await Product.findByIdAndDelete(id);
if (!deletedProduct) return res.status(404).json({
message: 'Product not found' });
res.status(200).json({ message: 'Product
deleted successfully' });
} catch (err) {
res.status(400).json({ error: err.message
});
}
});
// Start the server
app.listen(3000, () =>
{
console.log('Server is running on port 3000');
});
Testing the Application
1.
Start the server:
bash
CopyEdit
node app.js
2.
Test the CRUD operations
using Postman or any HTTP client:
o POST
request to add a new product.
o GET
request to retrieve all products.
o PUT
request to update an existing product.
o DELETE
request to remove a product.
Conclusion
This solution
demonstrates how to:
1.
Create a Mongoose schema and model.
2.
Implement CRUD operations (Create, Read,
Update, Delete) in a Node.js app.
3.
Use Mongoose to interact with MongoDB for
storing and manipulating data.
By completing these
tasks, students will get hands-on experience with building a Node.js
application using Mongoose for MongoDB.
4o mini
You said:
Write 10 assignments with
solution and explanation in detail on above concept
ChatGPT said:
ChatGPT
Assignments on CRUD
Operations with MongoDB and Mongoose
Below are 10 assignments
with detailed explanations and solutions to help students understand and
practice CRUD operations with MongoDB and Mongoose. These assignments will
focus on various scenarios, helping students solidify their understanding of
how to interact with a MongoDB database using Node.js and Mongoose.
Assignment 1: Create a
Mongoose Model for "Student"
Objective:
Create a schema and model for a "Student" collection. Each student
should have the following fields:
- name
(String): The name of the student.
- age
(Number): The age of the student.
- course
(String): The course the student is enrolled in.
- enrollmentDate
(Date): The date of enrollment.
Solution:
js
CopyEdit
const mongoose = require('mongoose');
const studentSchema = new
mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
course: {
type: String,
required: true
},
enrollmentDate: {
type: Date,
default: Date.now
}
});
const Student = mongoose.model('Student',
studentSchema);
Explanation:
This schema will create a Student model with the fields name, age, course, and enrollmentDate.
The enrollmentDate field defaults to the current date if not provided.
Assignment 2: Create a
New Student Document
Objective:
Write a function to add a new student to the database. Use the model created in
Assignment 1.
Solution:
js
CopyEdit
async function addStudent(name,
age, course) {
const student = new Student({
name,
age,
course
});
try {
const savedStudent = await student.save();
console.log("Student Added:",
savedStudent);
} catch (err) {
console.error("Error adding
student:", err);
}
}
Explanation:
This function takes name, age, and course as inputs, creates a new Student
instance, and saves it to the database using Mongoose's save() method.
Assignment 3: Display All
Students
Objective:
Write a function to fetch and display all student documents from the database.
Solution:
js
CopyEdit
async function getAllStudents()
{
try {
const students = await Student.find();
console.log("All Students:",
students);
} catch (err) {
console.error("Error fetching
students:", err);
}
}
Explanation:
The find() method retrieves all the documents from the Student collection. The
function logs the list of all students to the console.
Assignment 4: Find
Student by Name
Objective:
Write a function to find a student by their name.
Solution:
js
CopyEdit
async function findStudentByName(name)
{
try {
const student = await Student.findOne({
name });
if (!student) {
console.log("No student found with
the name:", name);
} else {
console.log("Student found:",
student);
}
} catch (err) {
console.error("Error finding
student:", err);
}
}
Explanation:
The findOne() method is used to find a single student by their name. If no
student is found, a message is logged.
Assignment 5: Update
Student Details
Objective:
Write a function to update the details of an existing student by their id.
Solution:
js
CopyEdit
async function updateStudent(id,
newDetails) {
try {
const updatedStudent = await Student.findByIdAndUpdate(id,
newDetails, { new: true });
if (!updatedStudent) {
console.log("No student found with
the ID:", id);
} else {
console.log("Updated Student:",
updatedStudent);
}
} catch (err) {
console.error("Error updating
student:", err);
}
}
Explanation:
The findByIdAndUpdate() method is used to find a student by their id and update
their details. The { new: true } option ensures the updated document is
returned.
Assignment 6: Delete a
Student by ID
Objective:
Write a function to delete a student by their id.
Solution:
js
CopyEdit
async function deleteStudentById(id)
{
try {
const deletedStudent = await Student.findByIdAndDelete(id);
if (!deletedStudent) {
console.log("No student found with
the ID:", id);
} else {
console.log("Deleted Student:",
deletedStudent);
}
} catch (err) {
console.error("Error deleting
student:", err);
}
}
Explanation:
The findByIdAndDelete() method is used to remove a student by their id from the
database.
Assignment 7: Display
Students Enrolled in a Specific Course
Objective:
Write a function to find students who are enrolled in a particular course.
Solution:
js
CopyEdit
async function findStudentsByCourse(course)
{
try {
const students = await Student.find({
course });
if (students.length === 0) {
console.log("No students found for
the course:", course);
} else {
console.log("Students enrolled
in", course, ":", students);
}
} catch (err) {
console.error("Error finding students
by course:", err);
}
}
Explanation:
The find() method is used to find all students enrolled in a specific course by
querying the course field.
Assignment 8: Add
Multiple Students at Once
Objective:
Write a function to add multiple students to the database at once.
Solution:
js
CopyEdit
async function addMultipleStudents(studentsArray)
{
try {
const savedStudents = await Student.insertMany(studentsArray);
console.log("Multiple Students
Added:", savedStudents);
} catch (err) {
console.error("Error adding multiple
students:", err);
}
}
Explanation:
The insertMany() method allows you to add an array of students at once. It
takes an array of objects and returns the inserted documents.
Assignment 9: Count the
Total Number of Students
Objective:
Write a function to count the total number of students in the database.
Solution:
js
CopyEdit
async function countStudents()
{
try {
const studentCount = await Student.countDocuments();
console.log("Total number of
students:", studentCount);
} catch (err) {
console.error("Error counting
students:", err);
}
}
Explanation:
The countDocuments() method returns the total number of documents in the
collection.
Assignment 10: List
Students Who Enrolled After a Specific Date
Objective:
Write a function to list students who enrolled after a given date.
Solution:
js
CopyEdit
async function studentsEnrolledAfter(date)
{
try {
const students = await Student.find({ enrollmentDate:
{ $gt: date } });
if (students.length === 0) {
console.log("No students found who
enrolled after", date);
} else {
console.log("Students enrolled
after", date, ":", students);
}
} catch (err) {
console.error("Error finding students
by enrollment date:", err);
}
}
Explanation:
The $gt operator in the query checks if the enrollmentDate is greater than the
given date.
Conclusion
These assignments allow
students to practice and implement basic CRUD operations with Mongoose and
MongoDB. Each assignment focuses on a specific operation, such as creating,
updating, deleting, and querying data, which helps build a strong foundation for
working with MongoDB in a Node.js environment.
4o mini
You said:
write 50 MCQs for the
concept above with explanation
ChatGPT said:
ChatGPT
Here are 50
multiple-choice questions (MCQs) with explanations related to the concept of CRUD
Operations with MongoDB and Mongoose.
MCQs on CRUD Operations
with MongoDB and Mongoose
1. What does CRUD stand
for?
- A)
Create, Retrieve, Update, Delete
- B)
Create, Read, Update, Delete
- C)
Collect, Retrieve, Update, Delete
- D)
Collect, Read, Update, Delete
Answer:
B) Create, Read, Update, Delete
Explanation: CRUD operations represent the basic operations performed on
a database: Create, Read, Update, and Delete.
2. Which method in
Mongoose is used to define a schema for a model?
- A)
.model()
- B)
.schema()
- C)
.define()
- D)
.create()
Answer:
B) .schema()
Explanation: .schema() is used in Mongoose to define the structure of a
document. It is then passed to .model() to create a model.
3. Which method is used
to add a new document to a MongoDB collection?
- A)
insert()
- B)
save()
- C)
create()
- D)
add()
Answer:
B) save()
Explanation: The .save() method is used to insert a new document into
the database in Mongoose.
4. Which of the following
is used to query all documents in a MongoDB collection with Mongoose?
- A)
find()
- B)
findOne()
- C)
get()
- D)
query()
Answer:
A) find()
Explanation: The .find() method is used to retrieve all documents from a
collection.
5. How can you retrieve a
single document based on a condition using Mongoose?
- A)
findOne()
- B)
findById()
- C)
getOne()
- D)
Both A and B
Answer:
D) Both A and B
Explanation: Both findOne() and findById() are used to retrieve a single
document, but findOne() allows you to use any query condition, while findById()
is specifically used to find by document ID.
6. What is the purpose of
the required field in a Mongoose schema?
- A)
Ensures the field is not null
- B)
Ensures the field is indexed
- C)
Ensures the field is unique
- D)
Ensures the field is populated in every document
Answer:
A) Ensures the field is not null
Explanation: The required option in a Mongoose schema ensures that a
field must have a value before the document can be saved to the database.
7. Which method would you
use to find documents with a specific value in a field?
- A)
find()
- B)
findOne()
- C)
findById()
- D)
findByField()
Answer:
A) find()
Explanation: The .find() method allows you to pass conditions to query
the database and find documents that match those conditions.
8. How do you update a
specific field of an existing document in Mongoose?
- A)
updateOne()
- B)
findByIdAndUpdate()
- C)
updateMany()
- D)
All of the above
Answer:
D) All of the above
Explanation: All these methods can be used to update documents. updateOne()
and updateMany() are for updating based on conditions, while findByIdAndUpdate()
finds a document by its ID and updates it.
9. Which Mongoose method
removes a document based on its ID?
- A)
deleteOne()
- B)
deleteById()
- C)
remove()
- D)
findByIdAndDelete()
Answer:
D) findByIdAndDelete()
Explanation: The findByIdAndDelete() method deletes a document based on
its unique ID.
10. What does the new:
true option in Mongoose's findByIdAndUpdate() method do?
- A)
It returns the document before it is updated
- B)
It updates the document and returns the new document
- C)
It returns the document after deleting it
- D)
It adds the new field to the document
Answer:
B) It updates the document and returns the new document
Explanation: The new: true option tells Mongoose to return the updated
document instead of the original.
11. How do you define a
default value for a field in Mongoose?
- A)
default: 'value'
- B)
value: 'default'
- C)
defaultValue: 'value'
- D)
value: {default: 'value'}
Answer:
A) default: 'value'
Explanation: The default option is used to set a default value for a
field when the document is created.
12. How do you limit the
number of documents returned in a query in Mongoose?
- A)
limit()
- B)
top()
- C)
take()
- D)
max()
Answer:
A) limit()
Explanation: The .limit() method is used to restrict the number of
documents returned by a query.
13. Which method is used
to count the total number of documents in a collection?
- A)
count()
- B)
countDocuments()
- C)
total()
- D)
countAll()
Answer:
B) countDocuments()
Explanation: The .countDocuments() method counts the total number of
documents that match a query condition in the collection.
14. What is the purpose
of the ObjectId type in Mongoose?
- A)
To create a unique identifier for each document
- B)
To store the actual data in the document
- C)
To define a new schema
- D)
To perform queries on documents
Answer:
A) To create a unique identifier for each document
Explanation: ObjectId is a special type in MongoDB that is used to store
a unique identifier for each document in the collection.
15. Which of the
following is the correct way to define a reference between two documents in
Mongoose?
- A)
type: ObjectId, ref: 'ModelName'
- B)
ref: 'ModelName', type: ObjectId
- C)
reference: 'ModelName', id: ObjectId
- D)
type: String, ref: 'ModelName'
Answer:
A) type: ObjectId, ref: 'ModelName'
Explanation: To create a reference between two documents, you define a
field as an ObjectId and use the ref option to specify the referenced model.
16. What is the purpose
of the populate() method in Mongoose?
- A)
To populate a document with random data
- B)
To populate fields in a document with data from referenced documents
- C)
To create multiple documents at once
- D)
To update multiple documents in the collection
Answer:
B) To populate fields in a document with data from referenced documents
Explanation: The .populate() method is used to replace the ObjectId
references with the actual documents from other collections.
17. Which of the
following is NOT a valid method to query documents in Mongoose?
- A)
findOne()
- B)
findById()
- C)
insertOne()
- D)
find()
Answer:
C) insertOne()
Explanation: insertOne() is not a valid method in Mongoose; instead, .save()
or .insertMany() are used for inserting documents.
18. How do you specify a
field as unique in a Mongoose schema?
- A)
unique: true
- B)
index: true
- C)
unique: 'field'
- D)
indexed: true
Answer:
A) unique: true
Explanation: The unique option ensures that a field has unique values in
the collection.
19. What method is used
to check if a document exists in the database?
- A)
findOne()
- B)
exists()
- C)
countDocuments()
- D)
check()
Answer:
A) findOne()
Explanation: The findOne() method is often used to check if a document
exists based on specific conditions.
20. What type of database
is MongoDB?
- A)
Relational Database
- B)
Key-Value Store
- C)
Document-Oriented Database
- D)
Column-Oriented Database
Answer:
C) Document-Oriented Database
Explanation: MongoDB is a NoSQL, document-oriented database, where data
is stored in flexible, JSON-like documents.
21. How would you create
a new collection in MongoDB using Mongoose?
- A)
Using db.createCollection()
- B)
Automatically when a document is saved
- C)
Using new Schema()
- D)
Using create() method
Answer:
B) Automatically when a document is saved
Explanation: MongoDB automatically creates a collection when the first
document is saved.
22. Which method is used
to modify multiple documents that match a condition in Mongoose?
- A)
updateMany()
- B)
updateAll()
- C)
modify()
- D)
change()
Answer:
A) updateMany()
Explanation: The .updateMany() method is used to update multiple
documents that match a specific query condition.
23. How do you add an
index to a field in a Mongoose schema?
- A)
index: true
- B)
indexed: true
- C)
unique: true
- D)
createIndex: true
Answer:
A) index: true
Explanation: The index: true option in a Mongoose schema defines an
index for the field.
24. What is the lean()
method used for in Mongoose?
- A)
Converts the result into a plain JavaScript object
- B)
Reduces the size of the document
- C)
Makes the query faster by not processing the results
- D)
Both A and C
Answer:
D) Both A and C
Explanation: The .lean() method returns plain JavaScript objects, making
queries faster and reducing memory usage since Mongoose doesn't need to create
document instances.
25. How would you
validate a field in Mongoose to ensure it is of a specific data type?
- A)
type: String
- B)
validate: /pattern/
- C)
type: Number
- D)
validate: 'type'
Answer:
A) type: String
Explanation: You can specify a field's data type in Mongoose by using
the type option (e.g., type: String, type: Number).
26. Which method is used
to remove all documents that match a condition in MongoDB?
- A)
deleteMany()
- B)
deleteAll()
- C)
removeAll()
- D)
remove()
Answer:
A) deleteMany()
Explanation: The .deleteMany() method is used to delete all documents
that match a query condition.
27. How can you ensure
data consistency in MongoDB when performing multiple operations?
- A)
Using Transactions
- B)
Using updateOne()
- C)
Using save()
- D)
Using atomic operations
Answer:
A) Using Transactions
Explanation: MongoDB supports transactions to ensure data consistency
across multiple operations.
28. Which method allows
you to update a single field of a document without replacing the entire
document?
- A)
updateOne()
- B)
set()
- C)
findByIdAndUpdate()
- D)
update()
Answer:
A) updateOne()
Explanation: The updateOne() method allows partial updates to a
document, updating only the fields that are passed in.
29. How do you return a
document that has been modified in MongoDB?
- A)
Using returnModified()
- B)
Using findOneAndUpdate()
- C)
Using save()
- D)
Using getUpdated()
Answer:
B) Using findOneAndUpdate()
Explanation: The findOneAndUpdate() method is used to find a document
and update it, and can be configured to return the updated document.
30. What does the validateBeforeSave
option do in Mongoose?
- A)
It skips the validation step before saving a document
- B)
It ensures validation happens before saving a document
- C)
It validates only the required fields
- D)
It saves the document without validating it
Answer:
B) It ensures validation happens before saving a document
Explanation: The validateBeforeSave option ensures that the document is
validated before being saved to the database.
31. Which method is used
to remove a specific document by its unique identifier?
- A)
removeById()
- B)
deleteById()
- C)
findByIdAndDelete()
- D)
removeOne()
Answer:
C) findByIdAndDelete()
Explanation: The findByIdAndDelete() method is used to find and delete a
document by its unique identifier.
32. What is the default
value of the timestamps option in Mongoose?
- A)
false
- B)
true
- C)
undefined
- D)
null
Answer:
B) true
Explanation: The timestamps option is enabled by default in Mongoose,
meaning fields createdAt and updatedAt are automatically created.
33. Which method would
you use to update an entire document with new data in Mongoose?
- A)
replaceOne()
- B)
updateOne()
- C)
findByIdAndUpdate()
- D)
update()
Answer:
A) replaceOne()
Explanation: The replaceOne() method completely replaces an existing
document with a new document.
34. What does the .exec()
method do in Mongoose?
- A)
Executes a query and returns a promise
- B)
Executes a query and returns the document immediately
- C)
Executes an aggregate operation
- D)
Creates a new document
Answer:
A) Executes a query and returns a promise
Explanation: The .exec() method executes the query and returns a
promise, allowing for asynchronous handling.
35. What is the default
data type of a field in Mongoose if not specified?
- A)
String
- B)
Number
- C)
Mixed
- D)
Undefined
Answer:
C) Mixed
Explanation: If a data type is not specified, the field is of the Mixed
type, which can store any value.
36. How do you delete a
single document using a condition in Mongoose?
- A)
deleteOne()
- B)
findOneAndDelete()
- C)
remove()
- D)
delete()
Answer:
A) deleteOne()
Explanation: The deleteOne() method deletes the first document that
matches the given condition.
37. How can you create a
new instance of a model in Mongoose?
- A)
Using new ModelName()
- B)
Using ModelName.create()
- C)
Using ModelName.save()
- D)
Using ModelName()
Answer:
A) Using new ModelName()
Explanation: In Mongoose, you create a new instance of a model by using
the new keyword followed by the model name, like new ModelName(). This creates
a new document instance that can be saved to the database later. The other
options (ModelName.create(), ModelName.save(), and ModelName()) are methods
used for different operations such as saving or directly creating and saving a
document.
38. What is the purpose
of the populate() method in Mongoose?
- A)
To join documents from multiple collections
- B)
To update a document
- C)
To validate a document
- D)
To count the number of documents
Answer:
A) To join documents from multiple collections
Explanation: The populate() method is used to perform a join between
collections by referencing documents from another collection.
39. How do you define a
unique index on a field in a Mongoose schema?
- A)
unique: true
- B)
index: true
- C)
uniqueIndex: true
- D)
index: 'unique'
Answer:
A) unique: true
Explanation: The unique: true option ensures that the values for a field
are unique across all documents in a collection.
40. Which method is used
to find a document by its primary key (ID) in Mongoose?
- A)
findOneById()
- B)
findById()
- C)
getById()
- D)
findOne()
Answer:
B) findById()
Explanation: The findById() method is used to find a document by its
primary key (ID).
41. Which of the
following is used to ensure a field in a Mongoose schema is required?
- A)
required: true
- B)
isRequired: true
- C)
need: true
- D)
mandatory: true
Answer:
A) required: true
Explanation: The required: true option ensures that the field is
mandatory when creating or updating a document.
42. How would you set a
default value for a field in Mongoose?
- A)
default: 'default_value'
- B)
value: 'default_value'
- C)
set: 'default_value'
- D)
initial: 'default_value'
Answer:
A) default: 'default_value'
Explanation: The default: 'default_value' option sets a default value
for the field if no value is provided when creating or updating a document.
43. How do you prevent
Mongoose from returning the _id field in a query result?
- A)
Use .select('-_id')
- B)
Use .exclude('_id')
- C)
Use .omit('_id')
- D)
Use .without('_id')
Answer:
A) Use .select('-_id')
Explanation: The .select('-_id') method excludes the _id field from the
query results.
44. What does the findOneAndUpdate()
method return by default in Mongoose?
- A)
The old document before update
- B)
The new document after update
- C)
A promise
- D)
The number of updated documents
Answer:
A) The old document before update
Explanation: By default, findOneAndUpdate() returns the document as it
was before the update.
45. How do you limit the
number of documents returned in a Mongoose query?
- A)
Use .limit(number)
- B)
Use .top(number)
- C)
Use .restrict(number)
- D)
Use .max(number)
Answer:
A) Use .limit(number)
Explanation: The .limit(number) method restricts the number of documents
returned by the query.
46. Which method allows
you to sort the documents in Mongoose?
- A)
.orderBy()
- B)
.sort()
- C)
.arrange()
- D)
.setOrder()
Answer:
B) .sort()
Explanation: The .sort() method allows sorting of documents based on the
specified field(s).
47. How do you add
validation to ensure a field is a valid email in Mongoose?
- A)
validate: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/
- B)
type: 'email'
- C)
validate: 'email'
- D)
regex: 'email'
Answer:
A) validate: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/
Explanation: The validate option with a regular expression can be used
to ensure a field contains a valid email format.
48. What is the result of
the findOne() method in Mongoose if no document is found?
- A)
It returns null
- B)
It throws an error
- C)
It returns an empty object
- D)
It returns undefined
Answer:
A) It returns null
Explanation: If no document matches the query, findOne() will return null.
49. Which method in
Mongoose is used to remove documents from a collection based on a condition?
- A)
deleteOne()
- B)
findByIdAndDelete()
- C)
remove()
- D)
deleteMany()
Answer:
D) deleteMany()
Explanation: The deleteMany() method is used to delete all documents
that match a query condition.
50. How would you enable
schema-level validation in Mongoose?
- A)
By using the validate option in the schema
- B)
By using schema.validate() method
- C)
By using mongoose.validation() method
- D)
By setting validation: true in schema options
Answer:
A) By using the validate option in the schema
Explanation: Schema-level validation is enabled by specifying the validate
option in a Mongoose schema field.

No comments:
Post a Comment