Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danmactough/2223677 to your computer and use it in GitHub Desktop.
Save danmactough/2223677 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
;
mongoose.connect('mongodb://localhost/test_update_getters_setters_defaults');
var Fooschema = new Schema ({
name : { type: String, default: 'foo', required: true }
, date : Date
, title: { type: String, required: true }
, count: { type: Number, default: 10, min: 10 }
});
Fooschema.path('title')
.get(function (){
return this.title.toUpperCase();
})
.set(function (v){
return v || 'Default Title';
});
var Foomodel = mongoose.model('Foo', Fooschema);
Foomodel.collection.drop();
var foo = new Foomodel( { name: 'Baz', title: '' });
console.log('New Foomodel:');
console.dir(foo);
foo.save(function(err){
if (err) console.error(err);
else {
console.log('Saved:');
console.dir(foo);
Foomodel.update({ _id: foo._id },
{ $set: { title: '' }, $inc: { count: -1 }, $unset: { name: 1 } },
function (err){
if (err) console.error(err);
else {
Foomodel.findById(foo._id, function (err, doc){
console.log('Updated:');
console.dir(doc);
Foomodel.update({ name: 'Bar' }, { $inc: { count: -5 } }, { upsert: true }, function (err){
if (err) console.error(err);
else {
Foomodel.findOne({ name: 'Bar' }, function (err, doc2){
console.log('Upserted:');
console.dir(doc2);
doc2.title = 'Doc2 title'; // <= [RangeError: Maximum call stack size exceeded]
doc2.count.$inc(10);
doc2.save(function (err){
if (err) console.error(err);
else {
console.log('Saved with atomic operator:');
console.dir(doc2);
}
});
});
}
});
});
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment