Created
March 12, 2013 01:40
-
-
Save azylman/5139583 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var DM, Document, PM, Property, Schema, assert, async, docs, mongoose; | |
mongoose = require('mongoose'); | |
Schema = mongoose.Schema; | |
async = require('async'); | |
assert = require('assert'); | |
mongoose.connect('localhost', 'simple_test'); | |
Document = new Schema({ | |
name: { | |
type: String, | |
required: true | |
} | |
}); | |
Property = new Schema({ | |
data: { | |
type: Schema.Types.Mixed, | |
required: true, | |
"default": {} | |
}, | |
doc: { | |
type: Schema.ObjectId, | |
required: true, | |
index: true, | |
ref: 'Document' | |
} | |
}); | |
Property.pre('save', function(next) { | |
console.log('pre save', this); | |
return next(); | |
}); | |
Property.post('save', function(doc, count) { | |
return console.log('post save', doc); | |
}); | |
DM = mongoose.model('Document', Document); | |
PM = mongoose.model('Property', Property); | |
docs = []; | |
docs.push(new DM({ | |
name: 'doc1' | |
})); | |
docs.push(new DM({ | |
name: 'doc2' | |
})); | |
async.waterfall([ | |
function(cb_wf) { | |
return async.forEach(docs, (function(doc, cb_fe) { | |
return doc.save(cb_fe); | |
}), cb_wf); | |
}, function(cb_wf) { | |
var prop; | |
console.log("CREATING PROP 1"); | |
prop = new PM({ | |
data: {}, | |
doc: docs[0]._id | |
}); | |
return prop.save(cb_wf); | |
}, function(prop, count, cb_wf) { | |
return PM.findById(prop._id, cb_wf); | |
}, function(prop, cb_wf) { | |
assert.deepEqual(prop.data, {}, "got " + (JSON.stringify(prop.data)) + " instead of {}"); | |
console.log("MODIFYING PROP 1"); | |
prop.data.my_key = 'my_value'; | |
prop.markModified('data'); | |
return prop.save(cb_wf); | |
}, function(prop, count, cb_wf) { | |
return PM.findById(prop._id, cb_wf); | |
}, function(prop, cb_wf) { | |
assert.deepEqual(prop.data, { | |
my_key: 'my_value' | |
}, "got " + (JSON.stringify(prop.data)) + " instead of {my_key: 'my_value'}"); | |
console.log("CREATING PROP 2"); | |
prop = new PM({ | |
data: {}, | |
doc: docs[1]._id | |
}); | |
return prop.save(cb_wf); | |
}, function(prop, count, cb_wf) { | |
return PM.findById(prop._id, cb_wf); | |
} | |
], function(err, prop) { | |
assert.deepEqual(prop.data, {}, "got " + (JSON.stringify(prop.data)) + " instead of {} for property " + (JSON.stringify(prop.toJSON()))); | |
return console.log("Done!"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Produces:
As you can see, the second property is stored in to mongo correctly according to its pre and post save handlers, but findById adds the same
data
property that we saved to the first property.