From aba7d0dc10647d0d4b0dd1dff355d3a05b664195 Mon Sep 17 00:00:00 2001 From: Pradnya Baviskar Date: Fri, 13 Feb 2015 18:30:36 +0530 Subject: [PATCH] Add $now as shortcut default value for date property --- lib/model.js | 4 +++- test/manipulation.test.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/model.js b/lib/model.js index dadb722d..513987c7 100644 --- a/lib/model.js +++ b/lib/model.js @@ -208,6 +208,7 @@ ModelBaseClass.prototype._initProperties = function (data, options) { for (k = 0; k < size; k++) { p = keys[k]; propVal = self.__data[p]; + var type = properties[p].type; // Set default values if (propVal === undefined) { @@ -222,6 +223,8 @@ ModelBaseClass.prototype._initProperties = function (data, options) { } else { def = def(); } + } else if (type.name === 'Date' && def === '$now') { + def = new Date(); } // FIXME: We should coerce the value // will implement it after we refactor the PropertyDefinition @@ -230,7 +233,6 @@ ModelBaseClass.prototype._initProperties = function (data, options) { } // Handle complex types (JSON/Object) - var type = properties[p].type; if (!BASE_TYPES[type.name]) { if (typeof self.__data[p] !== 'object' && self.__data[p]) { diff --git a/test/manipulation.test.js b/test/manipulation.test.js index b5af2d11..03a42d41 100644 --- a/test/manipulation.test.js +++ b/test/manipulation.test.js @@ -442,6 +442,35 @@ describe('manipulation', function () { person.isNewRecord().should.be.true; }); + it('should report current date when using $now as default value for date property', + function (done) { + var CustomModel = db.define('CustomModel', { + createdAt: { type: Date, default: '$now' } + }); + + var now = Date.now(); + + var myCustomModel = CustomModel.create(function (err, m) { + m.createdAt.should.be.instanceOf(Date); + (m.createdAt >= now).should.be.true; + }); + + done(); + }); + + it('should report \'$now\' when using $now as default value for string property', + function (done) { + var CustomModel = db.define('CustomModel', { + now: { type: String, default: '$now' } + }); + + var myCustomModel = CustomModel.create(function (err, m) { + m.now.should.be.instanceOf(String); + m.now.should.equal('$now'); + }); + + done(); + }); // it('should work when constructor called as function', function() { // var p = Person({name: 'John Resig'}); // p.should.be.an.instanceOf(Person);