MCPcopy
hub / github.com/sequelize/sequelize / findCreateFind

Method findCreateFind

lib/model.js:2400–2434  ·  lib/model.js::Model.findCreateFind

* A more performant findOrCreate that may not work under a transaction (working in postgres) * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again * * @see * {@link Model.findAll} for a full specification of find and options *

(options)

Source from the content-addressed store, hash-verified

2398 * @returns {Promise<Model,boolean>}
2399 */
2400 static async findCreateFind(options) {
2401 if (!options || !options.where) {
2402 throw new Error(
2403 class="st">'Missing where attribute in the options parameter passed to findCreateFind.'
2404 );
2405 }
2406
2407 let values = { ...options.defaults };
2408 if (_.isPlainObject(options.where)) {
2409 values = Utils.defaults(values, options.where);
2410 }
2411
2412
2413 const found = await this.findOne(options);
2414 if (found) return [found, false];
2415
2416 try {
2417 const createOptions = { ...options };
2418
2419 class="cm">// To avoid breaking a postgres transaction, run the create with `ignoreDuplicates`.
2420 if (this.sequelize.options.dialect === class="st">'postgres' && options.transaction) {
2421 createOptions.ignoreDuplicates = true;
2422 }
2423
2424 const created = await this.create(values, createOptions);
2425 return [created, true];
2426 } catch (err) {
2427 if (!(err instanceof sequelizeErrors.UniqueConstraintError || err instanceof sequelizeErrors.EmptyResultError)) {
2428 throw err;
2429 }
2430
2431 const foundAgain = await this.findOne(options);
2432 return [foundAgain, false];
2433 }
2434 }
2435
2436 /**
2437 * Insert or update a single row. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.

Callers 3

model.tsFile · 0.80
create.test.jsFile · 0.80

Calls 2

findOneMethod · 0.95
createMethod · 0.95

Tested by

no test coverage detected