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.