From 4e6351b8564a6f498f3a21809ac7ecf3ed3bf4e4 Mon Sep 17 00:00:00 2001 From: Amir Jafarian Date: Thu, 7 Apr 2016 18:22:46 -0400 Subject: [PATCH] Fix `forceId` check for `replaceById` --- lib/dao.js | 2 +- test/optional-validation.test.js | 38 ++++++++++++++++++++++++++++---- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/lib/dao.js b/lib/dao.js index 252ed4d2..b83612c6 100644 --- a/lib/dao.js +++ b/lib/dao.js @@ -2657,7 +2657,7 @@ DataAccessObject.replaceById = function(id, data, options, cb) { if (!data[pkName]) data[pkName] = id; var Model = this; - var inst = new Model(data); + var inst = new Model(data, { persisted: true }); var enforced = {}; this.applyProperties(enforced, inst); inst.setAttributes(enforced); diff --git a/test/optional-validation.test.js b/test/optional-validation.test.js index d80b76f8..f970d9b5 100644 --- a/test/optional-validation.test.js +++ b/test/optional-validation.test.js @@ -4,8 +4,9 @@ // License text available at https://opensource.org/licenses/MIT // This test written in mocha+should.js +var async = require('async'); var should = require('./init.js'); -var db, User, options, whereCount = 0; +var db, User, options, ModelWithForceId, whereCount = 0; var j = require('../'); var ValidationError = j.ValidationError; @@ -18,6 +19,10 @@ describe('optional-validation', function() { before(function(done) { db = getSchema(); + ModelWithForceId = db.createModel( + 'ModelWithForceId', + { name: String }, + { forceId: true }); User = db.define('User', { seq: { type: Number, index: true }, name: { type: String, index: true, sort: true }, @@ -27,9 +32,7 @@ describe('optional-validation', function() { order: { type: Number, index: true, sort: true }, vip: { type: Boolean }, }, { forceId: true, strict: true }); - - db.automigrate(['User'], done); - + db.automigrate(['ModelWithForceId', 'User'], done); }); beforeEach(function(done) { @@ -107,6 +110,33 @@ describe('optional-validation', function() { return { name: 'DoesNotExist' + (whereCount++) }; } + describe('forceId', function() { + context('replaceAttributes', function() { + it('should not fail if you do not pass the Primary key in data object', + function(done) { + ModelWithForceId.create({ name: 'foo' }, function(err, created) { + if (err) return done(err); + created.replaceAttributes({ name: 'bar' }, function(err, data) { + done(err); + }); + }); + }); + + it('should fail if you pass the Primary key in data object', + function(done) { + ModelWithForceId.create({ name: 'foo' }, function(err, created) { + if (err) return done(err); + created.replaceAttributes({ name: 'bar', id: 999 }, + function(err, data) { + should.exist(err); + done(); + }); + }); + }); + }); + }); + + describe('no model setting', function() { describe('method create', function() {