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()