findOne

The findOne() method is used to find a single document in the collection that matches the specified conditions. It returns 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.
  • 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 the found document represented as an object. If no document is found that matches the conditions, it resolves to 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 user = await this.findOne({
  conditions: { _id: ObjectId("638553506ba2ab03606eb77a") },
  projection: UserProtection.DEFAULT(),
  populate: UserPopulate.DEFAULT(),
  options: {
    sort: { createdAt: -1 },
    // ...
  },
});
In this example, findOne() is used in a UserService to retrieve a user based on their _id. The projection is defined by UserProjection.DEFAULT(), which likely specifies the fields to be included. Additional options for pagination and sorting are provided, along with a request to populate the profile field and to ignore archived documents.