Merge pull request #445 from PradnyaBaviskar/issue292

Add $now as shortcut default value for date property
This commit is contained in:
Miroslav Bajtoš 2015-02-17 19:46:05 +01:00
commit c939efe1e7
2 changed files with 32 additions and 1 deletions

View File

@ -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]) {

View File

@ -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);