Make sure id properties cannot be changed

This commit is contained in:
Raymond Feng 2015-03-16 09:25:38 -07:00
parent 7dc0fcd26f
commit 04348a1168
3 changed files with 41 additions and 2 deletions

View File

@ -1904,6 +1904,19 @@ DataAccessObject.prototype.updateAttributes = function updateAttributes(data, op
}
data = removeUndefined(data);
// Make sure id(s) cannot be changed
var idNames = Model.definition.idNames();
for (var i = 0, n = idNames.length; i < n; i++) {
var idName = idNames[i];
if (data[idName] !== undefined && data[idName] !== inst[idName]) {
var err = new Error('id property value cannot be updated: ' + idName);
err.statusCode = 400;
return process.nextTick(function() {
cb(err);
});
}
}
var context = {
Model: Model,
where: byIdQuery(Model, getIdValue(Model, inst)).where,

View File

@ -124,7 +124,7 @@ describe('datatypes', function () {
// update using updateAttributes
m.updateAttributes({
id: id, num: '10'
id: m.id, num: '10'
}, function (err, m) {
should.not.exist(err);
m.num.should.be.type('number');

View File

@ -425,7 +425,11 @@ describe('manipulation', function () {
before(function (done) {
Person.destroyAll(function () {
person = Person.create({name: 'Mary', age: 15}, done);
Person.create({name: 'Mary', age: 15}, function(err, p) {
should.not.exist(err);
person = p;
done();
});
});
});
@ -466,6 +470,28 @@ describe('manipulation', function () {
});
});
it('should allow same id value on updateAttributes', function(done) {
person.updateAttributes({id: person.id, name: 'John'},
function(err, p) {
should.not.exist(err);
Person.findById(p.id, function(e, p) {
should.not.exist(e);
p.name.should.equal('John');
p.age.should.equal(15);
done();
});
});
});
it('should fail if an id value is to be changed on updateAttributes',
function(done) {
person.updateAttributes({id: person.id + 1, name: 'John'},
function(err, p) {
should.exist(err);
done();
});
});
it('should allows model instance on updateAttributes', function(done) {
person.updateAttributes(new Person({'name': 'John', age: undefined}),
function(err, p) {