Node JS MongoDB Update
Updating documents in MongoDB with Node.js involves modifying existing records based on specified criteria. You can perform update operations using either the MongoDB native driver or Mongoose, an Object Data Modeling (ODM) library. Here’s a detailed guide on how to perform update operations with both methods.
1. Using MongoDB Native Driver
1.1 Set Up MongoDB Connection
Ensure you have MongoDB and the MongoDB native driver installed:
npm install mongodb
Code Example:
const { MongoClient } = require('mongodb');
// MongoDB URI and database name
const uri = 'mongodb://localhost:27017';
const databaseName = 'mydatabase';
async function updateDocuments() {
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// Connect to the MongoDB cluster
await client.connect();
console.log('Connected to MongoDB');
// Get a reference to the database and collection
const database = client.db(databaseName);
const collection = database.collection('mycollection');
// Update a single document
const result = await collection.updateOne(
{ name: 'Alice' }, // Filter
{ $set: { age: 29 } } // Update
);
console.log('Matched documents count:', result.matchedCount);
console.log('Modified documents count:', result.modifiedCount);
// Update multiple documents
const updateResult = await collection.updateMany(
{ age: { $gte: 30 } }, // Filter
{ $set: { status: 'Senior' } } // Update
);
console.log('Matched documents count (updateMany):', updateResult.matchedCount);
console.log('Modified documents count (updateMany):', updateResult.modifiedCount);
// Replace a document
const replaceResult = await collection.replaceOne(
{ name: 'Bob' }, // Filter
{ name: 'Bob', age: 35, email: 'bob@newdomain.com' } // New document
);
console.log('Matched documents count (replaceOne):', replaceResult.matchedCount);
console.log('Modified documents count (replaceOne):', replaceResult.modifiedCount);
} catch (error) {
console.error('Error:', error);
} finally {
// Close the connection
await client.close();
}
}
updateDocuments();
Explanation:
- Connect to MongoDB: Establish a connection to MongoDB using
MongoClient
. - Get Database and Collection: Access the database and collection where you want to perform the update.
- Update One Document: Use
updateOne()
to update a single document that matches the filter criteria. - Update Multiple Documents: Use
updateMany()
to update all documents that match the filter criteria. - Replace a Document: Use
replaceOne()
to replace an entire document with a new one based on the filter. - Close Connection: Close the MongoDB connection after the operation is complete.
Update Operators:
$set
: Sets the value of a field.$unset
: Removes a field.$inc
: Increments the value of a field.$push
: Adds an item to an array.$pull
: Removes an item from an array.
2. Using Mongoose
2.1 Set Up Mongoose
Install Mongoose if you haven’t already:
npm install mongoose
Code Example:
const mongoose = require('mongoose');
// MongoDB URI
const uri = 'mongodb://localhost:27017/mydatabase';
// Connect to MongoDB
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(error => console.error('Error connecting to MongoDB:', error));
// Define a schema and model
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String
});
const User = mongoose.model('User', userSchema);
async function updateDocuments() {
try {
// Update a single document
const result = await User.updateOne(
{ name: 'Alice' }, // Filter
{ $set: { age: 29 } } // Update
);
console.log('Matched documents count:', result.matchedCount);
console.log('Modified documents count:', result.modifiedCount);
// Update multiple documents
const updateResult = await User.updateMany(
{ age: { $gte: 30 } }, // Filter
{ $set: { status: 'Senior' } } // Update
);
console.log('Matched documents count (updateMany):', updateResult.matchedCount);
console.log('Modified documents count (updateMany):', updateResult.modifiedCount);
// Replace a document
const replaceResult = await User.replaceOne(
{ name: 'Bob' }, // Filter
{ name: 'Bob', age: 35, email: 'bob@newdomain.com' } // New document
);
console.log('Matched documents count (replaceOne):', replaceResult.matchedCount);
console.log('Modified documents count (replaceOne):', replaceResult.modifiedCount);
} catch (error) {
console.error('Error:', error);
} finally {
// Close the connection
await mongoose.connection.close();
}
}
updateDocuments();
Explanation:
- Connect to MongoDB: Use
mongoose.connect()
to establish a connection to MongoDB. - Define Schema and Model: Define a schema and create a model for the collection.
- Update One Document: Use
updateOne()
to update a single document. - Update Multiple Documents: Use
updateMany()
to update all matching documents. - Replace a Document: Use
replaceOne()
to replace an entire document. - Close Connection: Close the Mongoose connection after completing the operations.
Update Operators:
$set
: Sets the value of a field.$unset
: Removes a field.$inc
: Increments the value of a field.$push
: Adds an item to an array.$pull
: Removes an item from an array.
Best Practices
- Error Handling: Always handle errors during update operations to ensure the stability of your application.
- Indexing: Index fields used in queries to improve update performance.
- Atomic Operations: Use MongoDB’s atomic operations to ensure data consistency.
- Testing: Test update operations thoroughly to ensure they work as expected in different scenarios.