Database Queries with Mongoose
Overview
Mongoose provides a powerful way to interact with MongoDB through queries. You can retrieve, update, and delete documents using simple methods.
Finding Documents
You can find documents in a collection using the find()
method:
const User = require('./models/User'); // Assuming you have a User model
// Find all users
User.find()
.then(users => {
console.log('All Users:', users);
})
.catch(err => {
console.error('Error fetching users:', err);
});
Finding One Document
To find a single document, you can use the findOne()
method:
// Find a user by email
User.findOne({ email: 'john@example.com' })
.then(user => {
console.log('Found User:', user);
})
.catch(err => {
console.error('Error fetching user:', err);
});
Updating Documents
You can update documents using the updateOne()
or updateMany()
methods:
// Update a user's age
User.updateOne({ email: 'john@example.com' }, { age: 31 })
.then(result => {
console.log('Update Result:', result);
})
.catch(err => {
console.error('Error updating user:', err);
});
Deleting Documents
To delete a document, you can use the deleteOne()
or deleteMany()
methods:
// Delete a user by email
User.deleteOne({ email: 'john@example.com' })
.then(result => {
console.log('Delete Result:', result);
})
.catch(err => {
console.error('Error deleting user:', err);
});
Querying with Conditions
You can also query documents with specific conditions:
// Find users older than 25
User.find({ age: { $gt: 25 } })
.then(users => {
console.log('Users older than 25:', users);
})
.catch(err => {
console.error('Error fetching users:', err);
});