Back to Sails

`.updateOne()`

docs/reference/waterline/models/updateOne.md

12.12.20003.0 KB
Original Source

.updateOne()

Update the record that matches the given criteria, if such a record exists.

usage
var updatedRecord = await Something.updateOne(criteria)
.set(valuesToSet);

Before attempting to modify the database, Waterline will check to see if more than one record matches the given criteria; if so, it will throw an error instead of proceeding.

Usage

ArgumentTypeDetails
1criteria((dictionary))The Waterline criteria to use for matching the record in the database.
2valuesToSet((dictionary))A dictionary (plain JavaScript object) of values that all matching records should be updated to have. (Note that if this model is in "schemaful" mode, then any extraneous keys will be silently omitted.)

Note: For performance reasons, as of Sails v1.0 / Waterline 0.13, the valuesToSet object passed into this model method will be mutated in-place in most situations (whereas in Sails/Waterline v0.12, this was not necessarily the case).

Result
TypeDescription
((dictionary?))updateOne() never updates more than one record, so if a record is updated, then that record is provided as a result. Otherwise, undefined is returned.
Errors

See Concepts > Models and ORM > Errors for examples of negotiating errors in Sails and Waterline.

Example

javascript
var updatedUser = await User.updateOne({ firstName:'Pen' })
.set({
  firstName:'Finn'
});

if (updatedUser) {
  sails.log('Updated the user named "Pen" so that their new name is "Finn".');
}
else {
  sails.log('The database does not contain a user named "Pen".');
}

Notes

  • This method does not support .fetch(), because it always returns the modified record if one was matched.
  • This method can be used with await, promise chaining, or traditional Node callbacks.
  • This method can be used to replace an entire collection association (for example, a user’s list of friends), achieving the same result as the replaceCollection method. To modify items in a collection individually, use the addToCollection or removeFromCollection methods.
<docmeta name="displayName" value=".updateOne()"> <docmeta name="pageType" value="method">