updateOne

The updateOne() method is used to update a single document in the collection that matches the specified conditions. Unlike the update method, which can modify multiple documents, updateOne() targets only the first document that matches the conditions.

Arguments

  • conditions The criteria used to filter documents. It specifies the query conditions in the form of a JSON object.
  • changes (Object) The changes argument in updateOne() specifies modifications for the matching document. It’s an object where keys are field names, and values are new field values or update operators (e.g., set,set, unset, $inc) for advanced updates.
  • projection (Object | String): Determines which fields to include or exclude in the returned documents. It can be a string of space-separated field names or an object with field names as keys.
  • populate (Object | Array | String) Specifies the paths which should be populated with linked documents. Useful for retrieving related data.
  • options (Object) Offers an array of additional parameters for refining your query, such as ordering or limiting the number of results. You can utilize any Mongoose query options, allowing for extensive customization.

Returns

Returns a promise that resolves to the updated document when the operation completes successfully. If no documents match the specified conditions, updateOne() returns null.

Example

Service Definition
import { GenericCrudService } from "src/services/generic.crud.service";

@Injectable()
export class UserService extends GenericCrudService<UserDocument> {
  constructor(@InjectModel(User.name) readonly user: Model<UserDocument>) {
    super(user);
  }
}
Usage
const updatedDocument = await this.updateOne({
  conditions:  { _id: ObjectId("638553506ba2ab03606eb77a") }
  changes: { firstName: "John Doe" },
  projection: UserProjection.DEFAULT(),
  populate: UserPopulate.DEFAULT(),
  options: {} // Mongoose Query Options
}
);
In this example, updateOne() is used in a UserService to modify users details based on their _id. The method is passed the condition to match the specific user, the update object containing the firstName field, and the projection and populate objects to specify which fields to include in the returned document.