
Mongodb Update in NodeJs
Updating documents in MongoDB using Node.js can be done with:
β Native MongoDB Driver
πͺ Mongoose (if you're using schemas)
Letβs see both in action π
β 1. Using the Native MongoDB Driver
π¦ Install MongoDB driver
npm install mongodb
βοΈ Update Code Example
const { MongoClient } = require('mongodb');const uri = 'mongodb://localhost:27017';const client = new MongoClient(uri);async function updateUser() { try { await client.connect(); const db = client.db('myDatabase'); const users = db.collection('users'); // π Update one user const updateOne = await users.updateOne( { name: 'Alice' }, // Filter { $set: { age: 30 } } // Update ); console.log('Updated one:', updateOne.modifiedCount); // π Update many users const updateMany = await users.updateMany( { age: { $lt: 25 } }, { $set: { status: 'young' } } ); console.log('Updated many:', updateMany.modifiedCount); } finally { await client.close(); }}updateUser();
πͺ 2. Using Mongoose
π¦ Install Mongoose
npm install mongoose
βοΈ Update Code Example
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(() => console.log('Connected'));const userSchema = new mongoose.Schema({ name: String, age: Number, status: String });const User = mongoose.model('User', userSchema);async function updateUserMongoose() { // π Update one user await User.updateOne({ name: 'Bob' }, { $set: { age: 32 } }); // π Update many users await User.updateMany({ age: { $lt: 20 } }, { status: 'teen' }); console.log('Updates complete'); mongoose.disconnect();}updateUserMongoose();
π§ Useful MongoDB Update Operators
Operator | Meaning |
---|---|
$set | Set a new value |
$inc | Increment a value |
$unset | Remove a field |
$push | Add item to an array |
$pull | Remove item from an array |
π§ Bonus: Update & Return the New Doc (Mongoose)
const updated = await User.findOneAndUpdate( { name: 'Alice' }, { age: 35 }, { new: true } // returns the updated document);console.log(updated);
Let me know if youβd like to:
Create an update API route
Use dynamic update values
Validate data before update