MongoDB and Mongoose Flashcards

1
Q

How do you install and setup mongoose?

A

npm install mongoose
const mongoose = require(‘mongoose’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Where should you add your MongoDB URI?

A

a .env file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Show an example on how to set up mongoose and connect to a MongoDB database:

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

To create a model using mongoose, what do you need to do first?

A

need to define a schema that respresents the structure of your data, then you can create a model based on that schema.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Show what a schema would look like?(ex. “User”)
Then create the User model based on that schema:

A

// 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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What function do you use to create a mongoose schema?

A

mongoose.Schema()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What function do you use to create a mongoose model?

A

mongoose.model()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

In Node.js what is mongoose.Schema()?

A

is a function from Mongoose, which is a popular Object Data Modeling (ODM) library for MongoDB

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the use of model.Schema()?

A

is used to define the structure of documents within a collection in MongoDB through a set of key-type pairs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is mongoose.model()?

A

function is used to create a model based on a predefined schema.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the structure of mongoose.model()?

A

mongoose.model(‘name of model’, schema you want to base your model on)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Say you have a ‘User’ model,
const User = require(‘./userModel’),
Create and Save a record of this ‘User’ model:

A

// 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);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What can you use to create multiple records in mongoose?

A

model.create() method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

In mongoose what is model.create() method?

A

is a shortcut for creating new documents with the given objects and saving them to the database all in one go.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Show how creating many records with model.create() works:

A

// 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What can you use to search your database?

A

model.find() method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

In mongoose what is model.find()?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Using async/await, find all users with model.find():

A

async function findAllUsers() {
try {
const users = await User.find({});
console.log(‘Found users:’, users);
} catch (error) {
console.error(‘Error finding users:’, error);
}
}
findAllUsers();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Using async/await, find users with a specific condition with model.find(), ex. users aged 30 and above:

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

in mongoose how can you return a single matching document from your database?

A

model.findOne() method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is model.findOne()?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Assuming you have a User model defined, using async/await show how you would find a single user by username ‘john_doe’:

A

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’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

In mongoose, how can you search your database by _id?

A

model.findById() method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

In mongoose what is model.findById()?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

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?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is involved in performing a classic update operation?

A
  1. Finding the document you want to update.
  2. Editing the document in your application code.
  3. Saving the document back to the database.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

To update a document in MongoDB using Mongoose without manually finding, editing, and saving, What can you use instead?

A

model.findOneAndUpdate() method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is model.findOneAndUpdate()?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Show how to use model.findOneAndUpdate(), given that you want to update a username’s email:

A

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’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

When using model.findOneAndUpdate(), what do you need to make sure you do to return the updated document?

A

option should be ‘new: true’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

When using model.findOneAndUpdate(), what do you need to do if want to create a new document when no document matches the query criteria?

A

option should be ‘upsert: true’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

How can you delete one document in MongoDB using mongoose?

A

model.findByIdAndRemove()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is model.findByIdAndRemove()?

A

method in Mongoose is a convenience method for finding a document by its _id field and removing it from the database.

34
Q

Show how you can use model.findByIdAndRemove(), when trying to delete a userId of ‘12345’:

A

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

35
Q

How can you delete many documents in MongoDB with mongoose?

A

model.deleteMany()

36
Q

What is model.deleteMany()?

A

method is used to delete multiple documents from a MongoDB collection that match a specified condition or filter.

37
Q

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:

A

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

38
Q

In mongoose, what is one thing you can do to narrow down your results?

A

Chain search query helpers

39
Q

What are Query Helpers?

A

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.

40
Q

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

A

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);
});

41
Q

What is MongoDB?

A

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.

42
Q

What is mongoose?

A

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.

43
Q

Name some key points about mongoose:

A
  1. Schema Definition
  2. Model Creation
  3. CRUD Operation
  4. Validation
  5. Middleware
44
Q

In mongoose, what does CRUD stand for?

A

Create, Read, Update, Delete

45
Q

What query operator matches values that are equal to a specified value?

A

$eq

46
Q

What query operator matches values greater than a specified value?

A

$gt

47
Q

What query operator matches values greater than or equal to a specified value?

A

$gte

48
Q

What query operator matches values less than a specified value?

A

$lt

49
Q

What query operator matches values less than or equal to a specified value?

A

$lte

50
Q

What query operator matches values that are not equal to a specified value?

A

$ne

51
Q

What query operator matches any of the values specified in an array?

A

$in

52
Q

What query operator matches none of the values specified in a array?

A

$nin

53
Q

What query operator joins query clauses with a logical operator , returning all documents that match the coditions of both clauses?

A

$and

54
Q

What query operator inverts the effect of a query expression and returns documents that do not match the query expression?

A

$not

55
Q

What query operator joins query clauses with a logocal operator, returning all documents that fail to match both clauses?

A

$nor

56
Q

What query operator joins query clauses with a logical operator, returning all documents that match the conditions or either clause?

A

$or

57
Q

What query operator matches documents that have the specified field?

A

$exists

58
Q

What query operator matches documents if a field is of the specified type?

A

$type

59
Q

What query operator matches arrays that contain every elements specified in the query?

A

$all

60
Q

What query operator matches documents that contain an array field with at least one element that mathces all the specified query criteria?

A

$elemMatch

61
Q

What query operator matches any array with the number of elements specified by the query?

A

$size

62
Q

What query operator provides regular expression capabilities for pattern matching strings in queries?

A

$regex

63
Q

What query operator performs text search?

A

$text

64
Q

What query operator matches documents that satisfy a JavaScript expression?

A

$where

65
Q

What query operator sets the value of a field in a document?

A

$set

66
Q

What query operator removes the specified field from a document?

A

$unset

67
Q

What query operator increments the value of the field by the specified amount?

A

$inc

68
Q

What query operator adds an element to an array?

A

$push

69
Q

What query operator removes all instances of a value from an existing array?

A

$pull

70
Q

What query operator filters the document to pass only the documents that match the specified conditions(s) to the next pipeliine stage?

A

$match

71
Q

What query operator groups input documents by the specified identifier and applies the accumulator expressions?

A

$group

72
Q

What query operator passes along the documents with the requested fields to the next stage in the pipeline?

A

$project

73
Q

Which query helper method executes the query and returns a promise?

A

.exec()

74
Q

Which query helper method returns plain JavaScript objects instead of Mongoose documents(improves performance)?

A

.lean()

75
Q

Which query helper method specifies which field to include or exclude?

A

.select()

76
Q

Which query helper method populates refrenced documents from other collections?

A

.populate()

77
Q

Which query helper method specifies sorting order for query results?

A

.sort()

78
Q

Which query helper method specifies how many documents to skip?

A

.skip()

79
Q

Which query helper method specifies the maximum number of documents to return?

A

.limit()

80
Q
A