[ready] fixed; setting an unset default value #829

Merged
merged 1 commit into from Apr 12, 2012
Jump to file or symbol
Failed to load files and symbols.
+57 −4
Split
View
@@ -12,7 +12,7 @@ var EventEmitter = require('events').EventEmitter
, isMongooseObject = utils.isMongooseObject
, inspect = require('util').inspect
, StateMachine = require('./statemachine')
- , ActiveRoster = StateMachine.ctor('require', 'modify', 'init')
+ , ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default')
, deepEqual = utils.deepEqual
, hooks = require('hooks')
, DocumentArray
@@ -38,8 +38,8 @@ function Document (obj, fields) {
this._selected = fields;
}
- this._doc = this.buildDoc(fields);
this._activePaths = new ActiveRoster();
+ this._doc = this.buildDoc(fields);
var self = this;
this.schema.requiredPaths().forEach(function (path) {
self._activePaths.require(path);
@@ -149,15 +149,21 @@ Document.prototype.buildDoc = function (fields) {
if (p in fields) continue;
def = type.getDefault(self);
- if ('undefined' !== typeof def) doc_[piece] = def;
+ if ('undefined' !== typeof def) {
+ doc_[piece] = def;
+ self._activePaths.default(p);
+ }
} else {
// do nothing. only the fields specified in
// the query will be populated
}
} else {
def = type.getDefault(self);
- if ('undefined' !== typeof def) doc_[piece] = def;
+ if ('undefined' !== typeof def) {
+ doc_[piece] = def;
+ self._activePaths.default(p);
+ }
}
} else {
doc_ = doc_[piece] || (doc_[piece] = {});
@@ -430,6 +436,14 @@ Document.prototype.set = function (path, val, type) {
this.markModified(pathToMark);
} else if (!deepEqual(val, priorVal)) {
this.markModified(pathToMark);
+ } else if (!constructing &&
+ null != val &&
+ path in this._activePaths.states.default &&
+ deepEqual(val, schema.getDefault(this))) {
+ // special case:
+ // a path with a default was $unset on the server
+ // and the user is setting it to the same value again
+ this.markModified(pathToMark);
}
}
}
View
@@ -4590,5 +4590,44 @@ module.exports = {
affected.should.equal(1);
});
});
+ },
+
+ // gh-742
+ 'setting an unset default value is saved': function () {
+ var db = start();
+
+ var DefaultTestObject = db.model("defaultTestObject",
+ new Schema({
+ score:{type:Number, "default":55}
+ })
+ );
+
+ var myTest = new DefaultTestObject();
+
+ myTest.save(function (err, doc){
+ should.strictEqual(null, err);
+ should.equal(doc.score, 55);
+
+ DefaultTestObject.findById(doc._id, function (err, doc){
+ should.strictEqual(null, err);
+
+ doc.score = undefined; // unset
+ doc.save(function (err, doc, count){
+ should.strictEqual(null, err);
+
+ DefaultTestObject.findById(doc._id, function (err, doc){
+ should.strictEqual(null, err);
+
+ doc.score = 55;
+ doc.save(function (err, doc, count){
+ db.close();
+ should.strictEqual(null, err);
+ should.equal(doc.score, 55);
+ should.equal(count, 1);
+ });
+ });
+ });
+ });
+ })
}
};