create method and pass it the
attributes you want the model to have, or you can create a new instance of the
model and call its save method.
createdAt property will be filled with the
current timestamp if it’s not present.
If you want to update an existing model, you can also use the save method to
persist your changes.
save on an already existing model, the updatedAt field will be
filled with the current timestamp.
Updating multiple attributes
Instead of assigning each attribute individually and callingsave, you can
pass all the changes to the update method in one go.
update method assigns the given attributes to the model and saves it, so
the updatedAt field is filled with the current timestamp just like when you
call save yourself.
Both the timestamp properties contain the current time in milliseconds since
January 1st, 1970, using JavaScript’s
Date.now
method.
First or Create
Sometimes you may want to retrieve a model by certain attributes, or create it if it doesn’t exist. ThefirstOrCreate method will attempt to locate a model
using the given filter criteria. If the model is not found in the database, a
record will be created with the attributes from the filter, plus any additional
attributes passed as a second parameter.
firstOrCreate method’s first argument contains the attributes that you
want to search for. The second argument contains the additional attributes to
add to the model if it doesn’t exist. If the second argument is not provided,
the attributes from the first argument will be used when creating the model.
The lookup and the insert happen in a single atomic findOneAndUpdate
operation, and the returned model tells you what happened through its
wasRecentlyCreated property. It’s true when the model was just created and
false when an existing model was found, which makes it easy to keep track of
created and skipped records in a seed script.
wasRecentlyCreated is runtime metadata and is never stored in the database.
Models retrieved from the database always have it set to false. It’s also set
to true on models returned from create and on new instances after their
first save.
To be fully safe against duplicate inserts from concurrent callers, add a
unique index on the
filter fields. When two concurrent calls race, the losing call detects the
duplicate key error and returns the model the winning call inserted.
Increment & Decrement
When you only need to bump a numeric field, useincrement and decrement
directly on the query builder. They translate to MongoDB’s $inc operator and
respect the current where constraints.
