Overview
Thesave() method persists changes to your model instances. It works for both creating new models and updating existing ones, automatically handling timestamps and upsert operations.
Method Signature
packages/esix/src/base-model.ts
Creating New Models
When you callsave() on a new instance (without an id), Esix creates a new document in the database:
Updating Existing Models
When you callsave() on an existing model (with an id), Esix updates the existing document:
Automatic Timestamps
Thesave() method automatically manages timestamps:
- New models (no
id): SetscreatedAtto current time - Existing models (has
id): UpdatesupdatedAtto current time
Upsert Behavior
Esix uses MongoDB’s upsert functionality under the hood. This means:- If a document with the model’s
idexists, it gets updated - If no document exists, a new one is created
Working with Partial Updates
You can modify only specific fields and callsave() - unchanged fields remain intact:
Comparison with create()
There are two main approaches to creating models:Use
create() when you want to create and persist in a single operation. Use save() when you need more control over the model instance before persisting, or when updating existing models.