Edit Page

.findOrCreate()

Find the record matching the specified criteria. If no such record exists, create one using the provided initial values.

var newOrExistingRecord = await Something.findOrCreate(criteria, initialValues);

or, if you need to know whether a new record was created,

Something.findOrCreate(criteria, initialValues)
.exec(function(err, newOrExistingRecord, wasCreated) {

});

Usage

#
# Argument Type Details
1 criteria Dictionary? The Waterline criteria to use for matching records in the database. This particular criteria should always match exactly zero or one records in the database.
2 initialValues Dictionary The initial values for the new record, if one is created.

Callback

#
Argument Type Details
1 err Error? The error that occurred, or undefined if there were no errors.
2 newOrExistingRecord Dictionary? The record that was found, or undefined if no such record could be located.
3 wasCreated Boolean Whether a new record was created.
Errors
#
Name Type When?
UsageError Error Thrown if something invalid was passed in.
AdapterError Error Thrown if something went wrong in the database adapter.
Error Error Thrown if anything else unexpected happens.

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

Example

#

Let's make sure our test user, Finn, exists:

User.findOrCreate({ name: 'Finn' }, { name: 'Finn' })
.exec(async(err, user, wasCreated)=> {
  if (err) { return res.serverError(err); }

  if(wasCreated) {
    sails.log('Created a new user: ' + user.name);
  }
  else {
    sails.log('Found existing user: ' + user.name);
  }
});

Notes

#
  • This method can be used with await, promise chaining, or traditional Node callbacks. If you use await, be aware that the result will be the record only—you will not have access to wasCreated.
  • Behind the scenes, this uses .findOne(), so if more than one record in the database matches the provided criteria, there will be an error explaining so.

Is something missing?

If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.

Reference

Reference