MongoDB and Mongoose Flashcards
How do you install and setup mongoose?
npm install mongoose
const mongoose = require(‘mongoose’)
Where should you add your MongoDB URI?
a .env file
Show an example on how to set up mongoose and connect to a MongoDB database:
// Import mongoose library
const mongoose = require(‘mongoose’);
// Define the MongoDB connection URI.
const uri = process.env.MONGODB_URI;
// Connect to MongoDB
async function connectToDatabase() {
try {
await mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(‘Connected to MongoDB’);
} catch (error) {
console.error(‘Error connecting to MongoDB:’, error);
}
}
connectToDatabase();
To create a model using mongoose, what do you need to do first?
need to define a schema that respresents the structure of your data, then you can create a model based on that schema.
Show what a schema would look like?(ex. “User”)
Then create the User model based on that schema:
// Define the schema for the User model
const userSchema = new mongoose.Schema({
username: { type: String, required: true },
email: { type: String, required: true },
age: { type: Number, required: true },
createdAt: { type: Date, default: Date.now }
});
// Create the User model based on the schema
const User = mongoose.model(‘User’, userSchema);
// Export the User model to make it available in other files
module.exports = User;
What function do you use to create a mongoose schema?
mongoose.Schema()
What function do you use to create a mongoose model?
mongoose.model()
In Node.js what is mongoose.Schema()?
is a function from Mongoose, which is a popular Object Data Modeling (ODM) library for MongoDB
What is the use of model.Schema()?
is used to define the structure of documents within a collection in MongoDB through a set of key-type pairs.
What is mongoose.model()?
function is used to create a model based on a predefined schema.
What is the structure of mongoose.model()?
mongoose.model(‘name of model’, schema you want to base your model on)
Say you have a ‘User’ model,
const User = require(‘./userModel’),
Create and Save a record of this ‘User’ model:
// Create a new user document
const newUser = new User({
username: ‘john_doe’,
email: ‘john@example.com’,
age: 30
});
// Save the new user to the database
try {
const savedUser = await newUser.save();
console.log(‘User saved successfully:’, savedUser);
} catch (error) {
console.error(‘Error saving user:’, error);
}
What can you use to create multiple records in mongoose?
model.create() method
In mongoose what is model.create() method?
is a shortcut for creating new documents with the given objects and saving them to the database all in one go.
Show how creating many records with model.create() works:
// Array of user data
const usersData = [
{ username: ‘john_doe’, email: ‘john@example.com’, age: 30 },
{ username: ‘jane_smith’, email: ‘jane@example.com’, age: 25 },
{ username: ‘alice_wonderland’, email: ‘alice@example.com’, age: 35 }
];
// Create multiple user records
async function createUsers() {
try {
// Create multiple user records and wait for the promise to resolve
const createdUsers = await User.create(usersData);
console.log(‘Users created successfully:’, createdUsers);
} catch (error) {
console.error(‘Error creating users:’, error);
}
}
createUsers(); // Call the function to execute
What can you use to search your database?
model.find() method
In mongoose what is model.find()?
method in Mongoose is a powerful tool used for querying and retrieving data from a MongoDB database based on specified criteria. This method returns an array of documents that match the query criteria. If no documents match the criteria, it returns an empty array. If no criteria are provided, it returns all documents in the collection.
Using async/await, find all users with model.find():
async function findAllUsers() {
try {
const users = await User.find({});
console.log(‘Found users:’, users);
} catch (error) {
console.error(‘Error finding users:’, error);
}
}
findAllUsers();
Using async/await, find users with a specific condition with model.find(), ex. users aged 30 and above:
async function findUsersByAge() {
try {
const users = await User.find({ age: { $gte: 30 } });
console.log(‘Found users aged 30 and above:’, users);
} catch (error) {
console.error(‘Error finding users:’, error);
}
}
findUsersByAge();
in mongoose how can you return a single matching document from your database?
model.findOne() method
What is model.findOne()?
method in Mongoose is used to find a single document in a MongoDB collection that matches a specified query. model.findOne() returns only the first document that matches the criteria, or null if no match is found. This method is particularly useful when you need to retrieve a single document by some unique attribute, like a username or email address.
Assuming you have a User model defined, using async/await show how you would find a single user by username ‘john_doe’:
async function findUserByUsername(username) {
try {
const user = await User.findOne({ username: username });
if (user) {
console.log(‘Found user:’, user);
} else {
console.log(‘No user found with that username.’);
}
} catch (error) {
console.error(‘Error finding user:’, error);
}
}
findUserByUsername(‘john_doe’);
In mongoose, how can you search your database by _id?
model.findById() method
In mongoose what is model.findById()?
method in Mongoose is a specific and commonly used function that retrieves a single document by its unique _id field from a MongoDB collection. This method is particularly useful and efficient when you know the unique identifier (ObjectId) of the document you want to fetch. The _id field is automatically added by MongoDB to every document and is guaranteed to be unique within the collection.
Assuming you hava a ‘User’ model and a user’s _id of ‘507f1f77bcf86cd799439011’, usin async/await show how you would find a user by that ID?
async function findUserById(id) {
try {
const user = await User.findById(id);
if (user) {
console.log(‘Found user:’, user);
} else {
console.log(‘No user found with that ID.’);
}
} catch (error) {
console.error(‘Error finding user by ID:’, error);
}
}
const userId = ‘507f1f77bcf86cd799439011’;
findUserById(userId);
What is involved in performing a classic update operation?
- Finding the document you want to update.
- Editing the document in your application code.
- Saving the document back to the database.
To update a document in MongoDB using Mongoose without manually finding, editing, and saving, What can you use instead?
model.findOneAndUpdate() method
What is model.findOneAndUpdate()?
method in Mongoose is used to find a single document that matches a specified query, update it, and return the updated or original document, based on the options provided.
By default, findOneAndUpdate()
returns the document as it was before the update was applied, unless you set the new
option to true
, in which case it will return the document after the update.
Show how to use model.findOneAndUpdate(), given that you want to update a username’s email:
async function updateUserByUsername(username, newEmail) {
try {
const searchQuery = { username };
const update = { $set: { email: newEmail } };
const options = { new: true };
const updatedUser = await User.findOneAndUpdate(searchQuery, update, options);
if (updatedUser) {
console.log(‘Updated user:’, updatedUser);
} else {
console.log(‘User not found.’);
}
} catch (error) {
console.error(‘Error updating user:’, error);
}
}
updateUserByUsername(‘john_doe’, ‘john.doe@example.com’);
When using model.findOneAndUpdate(), what do you need to make sure you do to return the updated document?
option should be ‘new: true’
When using model.findOneAndUpdate(), what do you need to do if want to create a new document when no document matches the query criteria?
option should be ‘upsert: true’
How can you delete one document in MongoDB using mongoose?
model.findByIdAndRemove()
What is model.findByIdAndRemove()?
method in Mongoose is a convenience method for finding a document by its _id field and removing it from the database.
Show how you can use model.findByIdAndRemove(), when trying to delete a userId of ‘12345’:
async function deleteUserById(id) {
try {
const deletedUser = await User.findByIdAndRemove(id);
if (deletedUser) {
console.log(‘Deleted user:’, deletedUser);
} else {
console.log(‘No user found with that ID.’);
}
} catch (error) {
console.error(‘Error deleting user:’, error);
}
}
const userId = ‘12345’; // Example user ID
deleteUserById(userId);
How can you delete many documents in MongoDB with mongoose?
model.deleteMany()
What is model.deleteMany()?
method is used to delete multiple documents from a MongoDB collection that match a specified condition or filter.
Assuming you have a ‘User’ model, show how you can use model.deleteMany() to delete users with the age greater than or equal to 30:
async function deleteUsersByCondition(conditions) {
try {
const result = await User.remove(conditions);
console.log(‘Deleted users:’, result.deletedCount);
} catch (error) {
console.error(‘Error deleting users:’, error);
}
}
const conditions = { age: { $gte: 30 } }; // Example condition: delete users with age greater than or equal to 30
deleteUsersByCondition(conditions);
In mongoose, what is one thing you can do to narrow down your results?
Chain search query helpers
What are Query Helpers?
are methods that allow you to modify or refine your MongoDB queries before executing them. Chaining query helpers enables you to construct complex queries in a more readable and maintainable way.
Show an ex. using query helpers searching for certain users with the following:
-users with the age greater than or equal to 25
-find active users
-sort the results by createAt field
-limit the results to 10 documents
User.find()
.where(‘age’).gte(25) // Find users with age greater than or equal to 25
.where(‘isActive’).equals(true) // Find active users
.sort(‘createdAt’) // Sort the results by createdAt field
.limit(10) // Limit the results to 10 documents
.exec((error, users) => {
if (error) {
console.error(‘Error finding users:’, error);
return;
}
console.log(‘Found users:’, users);
});
What is MongoDB?
is a popular open-source, NoSQL database that uses a document-oriented data model. Instead of tables and rows like in traditional relational databases, MongoDB stores data in flexible, JSON-like documents with dynamic schemas, making it easy to store and retrieve complex data structures. It’s known for its scalability, flexibility, and ease of use.
What is mongoose?
is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a higher-level abstraction over MongoDB’s native driver, allowing developers to define schemas, models, and relationships in a more structured way. Mongoose simplifies interactions with MongoDB databases by providing features such as validation, middleware, query building, and more.
Name some key points about mongoose:
- Schema Definition
- Model Creation
- CRUD Operation
- Validation
- Middleware
In mongoose, what does CRUD stand for?
Create, Read, Update, Delete
What query operator matches values that are equal to a specified value?
$eq
What query operator matches values greater than a specified value?
$gt
What query operator matches values greater than or equal to a specified value?
$gte
What query operator matches values less than a specified value?
$lt
What query operator matches values less than or equal to a specified value?
$lte
What query operator matches values that are not equal to a specified value?
$ne
What query operator matches any of the values specified in an array?
$in
What query operator matches none of the values specified in a array?
$nin
What query operator joins query clauses with a logical operator , returning all documents that match the coditions of both clauses?
$and
What query operator inverts the effect of a query expression and returns documents that do not match the query expression?
$not
What query operator joins query clauses with a logocal operator, returning all documents that fail to match both clauses?
$nor
What query operator joins query clauses with a logical operator, returning all documents that match the conditions or either clause?
$or
What query operator matches documents that have the specified field?
$exists
What query operator matches documents if a field is of the specified type?
$type
What query operator matches arrays that contain every elements specified in the query?
$all
What query operator matches documents that contain an array field with at least one element that mathces all the specified query criteria?
$elemMatch
What query operator matches any array with the number of elements specified by the query?
$size
What query operator provides regular expression capabilities for pattern matching strings in queries?
$regex
What query operator performs text search?
$text
What query operator matches documents that satisfy a JavaScript expression?
$where
What query operator sets the value of a field in a document?
$set
What query operator removes the specified field from a document?
$unset
What query operator increments the value of the field by the specified amount?
$inc
What query operator adds an element to an array?
$push
What query operator removes all instances of a value from an existing array?
$pull
What query operator filters the document to pass only the documents that match the specified conditions(s) to the next pipeliine stage?
$match
What query operator groups input documents by the specified identifier and applies the accumulator expressions?
$group
What query operator passes along the documents with the requested fields to the next stage in the pipeline?
$project
Which query helper method executes the query and returns a promise?
.exec()
Which query helper method returns plain JavaScript objects instead of Mongoose documents(improves performance)?
.lean()
Which query helper method specifies which field to include or exclude?
.select()
Which query helper method populates refrenced documents from other collections?
.populate()
Which query helper method specifies sorting order for query results?
.sort()
Which query helper method specifies how many documents to skip?
.skip()
Which query helper method specifies the maximum number of documents to return?
.limit()