.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) {
});
# | Argument | Type | Details |
---|---|---|---|
1 | criteria | 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 | The initial values for the new record, if one is created. |
Argument | Type | Details | |
---|---|---|---|
1 | err | The error that occurred, or undefined if there were no errors. |
|
2 | newOrExistingRecord | The record that was found, or undefined if no such record could be located. |
|
3 | wasCreated | Whether a new record was created. |
Name | Type | When? |
---|---|---|
UsageError | Thrown if something invalid was passed in. | |
AdapterError | Thrown if something went wrong in the database adapter. | |
Error | Thrown if anything else unexpected happens. |
See Concepts > Models and ORM > Errors for examples of negotiating errors in Sails and Waterline.
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);
}
});
- This method can be used with
await
, promise chaining, or traditional Node callbacks. If you useawait
, be aware that the result will be the record only—you will not have access towasCreated
.- 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.