updateOne

The updateMany() method is used to update multiple documents in a collection that match the specified conditions. It targets all documents meeting the criteria, as opposed to updateOne(), which only affects the first matching document.

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 an object containing information about the operation, such as the number of documents affected. If no documents match the specified conditions, the returned object will indicate that no documents were updated.

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 updateResult = await this.updateMany({
  conditions: { status: "inactive" },
  changes: { status: "active" },
  projection: UserProjection.DEFAULT(),
  populate: UserPopulate.DEFAULT(),
  options: {}, // Mongoose Query Options
});
In this example, updateMany() is used in a UserService to update the status of all users from “inactive” to “active”. The method is passed the condition to match specific users and the update object containing the status field. The result will indicate how many documents were updated.