From 5b0ea8b46905814e98d10597a015b8d345b8549a Mon Sep 17 00:00:00 2001 From: Cody Stoltman Date: Thu, 27 Oct 2016 16:02:01 -0500 Subject: [PATCH] don't error out if the join record already exists --- .../model/lib/associationMethods/add.js | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/waterline/model/lib/associationMethods/add.js b/lib/waterline/model/lib/associationMethods/add.js index e494492d8..2e5d5e69d 100644 --- a/lib/waterline/model/lib/associationMethods/add.js +++ b/lib/waterline/model/lib/associationMethods/add.js @@ -340,14 +340,24 @@ Add.prototype.createManyToMany = function(collection, attribute, pk, key, cb) { // First look up the record to ensure it doesn't exist collection.findOne(criteria, function(err, val) { - if (err || val) { - return next(new Error('Trying to \'.add()\' an instance which already exists!')); + if (err) { + return next(err); } - next(); + + next(null, val); }); }, - createRecord: ['validateAssociation', 'validateRecord', function(next) { + createRecord: ['validateAssociation', 'validateRecord', function(next, results) { + // If the record already exists, don't try and create it again to prevent + // duplicates. + var validateRecord = results.validateRecord; + if (validateRecord) { + return async.setImmediate(function() { + next(); + }); + } + collection.create(_values, next); }]