Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created August 20, 2012 18:45
Show Gist options
  • Save aheckmann/3406579 to your computer and use it in GitHub Desktop.
Save aheckmann/3406579 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var assert = require('assert')
console.log('\n===========');
console.log(' mongoose version: %s', mongoose.version);
console.log('========\n\n');
mongoose.set('debug', true);
mongoose.connect('localhost', 'testing_1062');
mongoose.connection.on('error', function () {
console.error('connection error', arguments);
});
var schema = new Schema({
category: { type: String, unique: true }
, counts: {}
});
schema.statics.test = function (category, keys, cb) {
var conditions = {'category': category};
var update = {'$inc': {'counts.total': 1}};
var options = {'safe': true, 'upsert': true, 'multi': false};
var key;
for (var i = 0, len = keys.length; i < len; i++) {
key = keys[i];
update['$inc']['counts.' + key] = 1;
}
return this.update(conditions, update, options, cb);
}
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
mongoose.connection.db.dropDatabase(function () {
var a = new A({ category: 'testing' });
a.save(function (err, a) {
if (err) return done(err);
A.test('testing', 'a b.e.f c'.split(' '), function (err, numAffected) {
console.error(arguments);
done(err);
});
})
})
});
function done (err) {
if (err) console.error(err.stack);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment