Implement findOrCreate, requested in #190
This commit is contained in:
parent
40b64cfc5e
commit
9dbc8fa50b
|
@ -258,6 +258,34 @@ AbstractClass.upsert = AbstractClass.updateOrCreate = function upsert(data, call
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find one record, same as `all`, limited by 1 and return object, not collection,
|
||||||
|
* if not found, create using data provided as second argument
|
||||||
|
*
|
||||||
|
* @param {Object} query - search conditions: {where: {test: 'me'}}.
|
||||||
|
* @param {Object} data - object to create.
|
||||||
|
* @param {Function} cb - callback called with (err, instance)
|
||||||
|
*/
|
||||||
|
AbstractClass.findOrCreate = function findOrCreate(query, data, callback) {
|
||||||
|
if (typeof query === 'undefined') {
|
||||||
|
query = {where: {}};
|
||||||
|
}
|
||||||
|
if (typeof data === 'function' || typeof data === 'undefined') {
|
||||||
|
callback = data;
|
||||||
|
data = query && query.where;
|
||||||
|
}
|
||||||
|
if (typeof callback === 'undefined') {
|
||||||
|
callback = function () {};
|
||||||
|
}
|
||||||
|
|
||||||
|
var t = this;
|
||||||
|
this.findOne(query, function (err, record) {
|
||||||
|
if (err) return callback(err);
|
||||||
|
if (record) return callback(null, record);
|
||||||
|
t.create(data, callback);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check whether object exitst in database
|
* Check whether object exitst in database
|
||||||
*
|
*
|
||||||
|
@ -341,7 +369,7 @@ AbstractClass.all = function all(params, cb) {
|
||||||
/**
|
/**
|
||||||
* Find one record, same as `all`, limited by 1 and return object, not collection
|
* Find one record, same as `all`, limited by 1 and return object, not collection
|
||||||
*
|
*
|
||||||
* @param {Object} params - search conditions
|
* @param {Object} params - search conditions: {where: {test: 'me'}}
|
||||||
* @param {Function} cb - callback called with (err, instance)
|
* @param {Function} cb - callback called with (err, instance)
|
||||||
*/
|
*/
|
||||||
AbstractClass.findOne = function findOne(params, cb) {
|
AbstractClass.findOne = function findOne(params, cb) {
|
||||||
|
|
Loading…
Reference in New Issue