find

The find() method is used to find multiple documents in a collection that match the specified conditions. It returns an array of documents that match the criteria.

Arguments

  • conditions The criteria used to filter documents. Specifies the query conditions in the form of a JSON object.
  • 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.
  • ignoreArchived (Boolean) If set to true, the query will ignore archived documents. Defaults to false.

Returns

Resolves to an array of found documents represented as objects. If no documents are found that match the conditions, it resolves to an empty array.

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 users = await this.find({
  conditions: { setupCompleted: true },
  projection: UserProjection.DEFAULT(),
  populate: UserPopulate.DEFAULT(),
  options: {
    skip: 0,
    limit: 50,
    sort: { firstName: 1 },
  },
  ignoreArchived: true, // archived users will be included in the result
});
In this example, we are using the find() method to retrieve all users that have completed the setup process. We are also using the projection and populate arguments to specify which fields should be included in the result and which fields should be populated with related data. Lastly, we are using the options argument to specify the order of the results and to limit the number of results to 50.