5

I have a collection that has a username as a field. The Model defines this field to be unique. However I was able to insert a duplicate value in the database.

class Profile
  include Mongoid::Document
  include Mongoid::Paperclip

  field :username
  index({ username: 1 } , { unique: true })
end

The Collection however has 2 usernames that are the same

{ "_id" : ObjectId( "50b3b323421aa95da6000004" ),
  "username" : "marceloreuse" }

{ "_id" : ObjectId( "50b3b567421aa93d84000002" ),
  "username" : "marceloreuse" }

What went wrong here?

4
  • your example also shows the same exact ObjectId's - is that correct or a copy/paste oversight?
    – kmfk
    Nov 26, 2012 at 18:55
  • my bad... that was a copy paste issue
    – Amit
    Nov 26, 2012 at 18:58
  • Out of curiosity - this is not a sharded colleciton, is it?
    – kmfk
    Nov 26, 2012 at 19:34
  • no, its a normal collection
    – Amit
    Nov 27, 2012 at 13:41

1 Answer 1

11

I would double check your indexes - from the console try db.collection.getIndexes() and make sure your index is present.

In case you missed it, Mongoid doesn't auto build the index because you specified it - you need to run the included: rake db:mongoid:create_indexes.

2
  • However, mongoid is still not throwing an error when adding a duplicate entry. The entry is not added, but mongoid is not giving any errors.
    – Amit
    Nov 27, 2012 at 13:42
  • That's due to the default write concern in MongoDB - the driver won't wait for a response - meaning you need to either call getLastError or change your persistence settings persist_in_safe_mode. Check out Mongoid: Persistence - Safe Mode.
    – kmfk
    Nov 27, 2012 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.