Skip to content

Commit

Permalink
Fixes property defaultValue not being set if property is null (closes #…
Browse files Browse the repository at this point in the history
…104)

Added a test for this and fixed another one.
  • Loading branch information
dresende committed Apr 8, 2013
1 parent 611fca8 commit 87d6389
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 4 deletions.
7 changes: 7 additions & 0 deletions lib/Instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ function Instance(opts) {
return saveInstanceExtra(cb);
}

for (var k in opts.properties) {
if (!opts.properties.hasOwnProperty(k)) continue;
if (opts.data[k] == null && opts.properties[k].hasOwnProperty("defaultValue")) {
opts.data[k] = opts.properties[k].defaultValue;
}
}

if (opts.is_new || !opts.data.hasOwnProperty(opts.id)) {
Hook.trigger(instance, opts.hooks.beforeCreate);
}
Expand Down
2 changes: 1 addition & 1 deletion test/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ common.getConnectionString = function () {

common.getModelProperties = function () {
return {
name: String
name: { type: "text", defaultValue: "test_default_value" }
};
};

Expand Down
20 changes: 20 additions & 0 deletions test/integration/test-create-defaultvalue.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var common = require('../common');
var assert = require('assert');

common.createConnection(function (err, db) {
common.createModelTable('test_create_defaultvalue', db.driver.db, function () {
var TestModel = db.define('test_create_defaultvalue', common.getModelProperties());

TestModel.create([
{ name: null }
], function (err) {
TestModel.find(function (err, items) {
assert.equal(err, null);
assert.equal(Array.isArray(items), true);
assert.equal(items.length, 1);
assert.equal(items[0].name, "test_default_value");
db.close();
});
});
});
});
4 changes: 1 addition & 3 deletions test/integration/test-hook-before-create-define-property.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ common.createConnection(function (err, db) {
var TestModel = db.define('test_hook_before_create_define_property', common.getModelProperties(), {
hooks: {
beforeCreate: function () {
if (!this.name) {
this.name = name;
}
this.name = name;
}
}
});
Expand Down

0 comments on commit 87d6389

Please sign in to comment.