create

The create() method is used to create and insert a new document into the collection. It takes an object or an array of objects representing the new document(s) and adds them to the collection.

Arguments

  • document An object or an array of objects representing the new document(s) to be created. Each object should match the schema of the collection.
  • 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

Resolves to the created document object or an array of document objects if multiple documents were created. Each object will include fields specified in the schema, including automatically generated fields like _id.

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 createdDocument = await this.create({
  document: { firstName: "John Doe", email: "john.doe@example.com" },
  projection: UserProtection.DASHBOARD(),
  populate: UserPopulate.DASHBOARD(),
});
In this example, create() is used in a UserService to create a new user. The method is passed an object containing the new user’s details, which should align with the user schema. Once executed, the method returns the newly created user document, including its generated _id and any default values specified in the schema.