Skip to content

Instantly share code, notes, and snippets.

@jeremys
Created June 22, 2011 16:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremys/1040469 to your computer and use it in GitHub Desktop.
Save jeremys/1040469 to your computer and use it in GitHub Desktop.
Index/Save conflict
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/db');
var User = new Schema({
email: { 'type': String, 'required': true, 'index': { 'unique': true, 'background': true } },
});
User = mongoose.model('User', User);
var newUser = new User();
newUser.email = 'john@doe.com';
newUser.save(function (err) {
console.log('saved');
});
newUser = new User();
newUser.email = 'john@doe.com';
newUser.save(function (err) {
console.log('saved');
});
Model.init = function () {
// build indexes
var self = this
, indexes = this.schema.indexes
, count = indexes.length;
indexes.forEach(function (index) {
self.collection.ensureIndex(index[0], index[1], function(){
--count || self.emit('index');
console.log('index finished');
});
});
};
$ node conflict.js
saved
saved
index finished
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment