The Model.updateOne()
function in Mongoose is a crucial method used to update single documents within the database. This functionality has been part of Mongoose since it introduced the ability to perform update operations on models, following MongoDB’s updateOne
operation, which was added in version 3.2 released in December 2015.
The main purpose of updateOne()
is to update the first document that matches the given filter in a collection. It’s a shorthand for the standard update
operation with the { multi: false }
option, ensuring only one document is updated.
Overview
The syntax, parameters, and return value of updateOne()
.
Syntax:
Model.updateOne(query, update, [options], [callback])
Parameters:
query
: The selection criteria for the update.-
update
: The modifications to apply. options
: Optional settings.callback
: Optional callback for executing the query.
The returned value is a promise that resolves to an object containing the outcome of the operation.
Examples
Below are some practical examples of how to use Model.updateOne()
in a Node.js application with Mongoose:
Example 1: Basic Update Operation
This example performs a straightforward update on a single document matching specific criteria:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const userSchema = new Schema({ username: String, lastLogin: Date });
const User = mongoose.model('User', userSchema);
async function updateLastLogin(username) {
await User.updateOne(
{ username },
{ $set: { lastLogin: new Date() } }
);
console.log('User last login date updated.');
}
await updateLastLogin('johndoe');
This approach is most beneficial when you know that only one document will ever match the criteria, or you only care about the first match being updated.
Example 2: Conditional Upsert
This example demonstrates how to updates a specific field for a document or creates the document if it doesn’t exist:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const statusSchema = new Schema({ userId: mongoose.Types.ObjectId, statusText: String });
const Status = mongoose.model('Status', statusSchema);
async function upsertStatus(userId, statusText) {
await Status.updateOne(
{ userId },
{ $set: { statusText } },
{ upsert: true }
);
console.log('Status updated or created.');
}
await upsertStatus(new mongoose.Types.ObjectId('1234567890abcdef4ghijk'), 'Feeling great!');
The use of the upsert
option ensures that if no existing document matches the query, a new document will be created using both the query and the update object.
Conclusion
The Mongoose Model.updateOne()
function is an essential tool for making single document updates. Its precision and atomicity ensure reliable updates with minimal effort. The above examples provide an understanding of basic usage and more advanced options like upserting. With Mongoose and Node.js, managing document updates can be done efficiently and concisely.