Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Created September 13, 2011 05:30
Show Gist options
  • Save ricardobeat/1213187 to your computer and use it in GitHub Desktop.
Save ricardobeat/1213187 to your computer and use it in GitHub Desktop.
MongoDB - test compound indexes on embedded documents
var mongoose = require('mongoose')
, Schema = mongoose.Schema
mongoose.connect('mongodb://localhost/identities');
var IdentitySchema = new Schema({
type : { type: String, enum: ['twitter', 'facebook', 'google'] }
, uid : { type: String }
})
var UserSchema = new Schema({
identities : [ IdentitySchema ]
})
UserSchema.index({ "identities.type": 1, "identities.uid" : 1 }, { unique: true })
var User = mongoose.model('User', UserSchema)
// clean up db before tests
User.remove({}, function(){
// creates an user from identities array
function testUserInsert(){
var user = new User()
, identities = [].slice.call(arguments)
identities.forEach(function(id){
user.identities.push(id)
})
user.save(function(err){
if (err){
console.log("error creating user\n", identities, "\n", err.message)
} else {
console.log("user created\n", identities)
}
})
}
// multiple ids
testUserInsert(
{ uid: 'Jim', type: 'twitter' }
, { uid: 'Jim', type: 'facebook' }
)
// different service, ok
testUserInsert(
{ uid: 'Jim', type: 'google' }
)
// same service, should raise an error
testUserInsert(
{ uid: 'Jim', type: 'twitter' }
)
})
@elliotf
Copy link

elliotf commented Feb 10, 2013

For anyone else that gets here from google:

The problem is that indexes are created in the background by default.

In order to get this to fail, I had to call ensureIndexes:

http://mongoosejs.com/docs/api.html#model_Model.ensureIndexes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment