3

I am working with Twitter authentication and want to store the twitter id as unique key in mongodb. However i see multiple entries with the same id. Here's my schema and code

Schema:

var TwitterSchema = new Schema({
    accessToken: String,
    accessTokenSecret: String,
    name: String,
    twitterId: { type: String, required: true, index: { unique: true, sparse: true } }
});

Code:

        mongoose.connect('mongodb://localhost/twd')
        mongoose.model('Post', TwitterSchema);    
        var Post = mongoose.model('Post');

        var post = new Post();
        post.accessToken = accessToken
        post.accessTokenSecret = accessTokenSecret
        post.name = twitterUserData.name
        post.twitterId = twitterUserData.id

        post.save(function(err){
            if (err){
                throw err;
                promise.fail(err);
             }
            console.log('saved');
            mongoose.disconnect();
        });

        promise.fulfill(post);

DB shell output

> db.posts.find();
{ "twitterId" : "21475255", "name" : "MMMK", "accessTokenSecret" : "ZYhiXMWfXvSr1aaCB93hgU243j8aapP0ALdSFlWEE", "accessToken" : "22475255-9YvKMceUInUIxcEtKAK0oMRRG2ZZxn5c52vnwPw", "_id" : ObjectId("4feddf6155203990e000001") }
{ "twitterId" : "21475255", "name" : "MMMK, "accessTokenSecret" : "ZYhiXMWfXvSr1aaCB93hgU2438aapP0ALdSFlWEE", "accessToken" : "22475255-9YvKMceUInUIxcEtKAK0oMRRG2ZZxn5c52vnwPw", "_id" : ObjectId("4feddf7b5905a1a10e000001") }
1
  • Can you include the output of db.posts.getIndexes();? That would confirm whether the expected unique index actually exists. Commented Jul 3, 2012 at 3:15

1 Answer 1

1

My guess is either the index isn't being created in MongoDB, or the index with the same name already exits. If it already exists, mongoose will use ensureIndex to create it, but that won't override/redefine it if it already exists. Use the mongo js shell to see if it exists, then try dropping it, restarting mongod, and running your node.js code again.

http://www.mongodb.org/display/DOCS/Indexes#Indexes-CreationOptions

Sign up to request clarification or add additional context in comments.

3 Comments

I tried restarting mongodb but didn't work. Not sure where's the problem. Added output from db shell
Have you also tried dropping the existing index on twitterId like Peter suggested to ensure it's created as you have it currently defined?
A new unique index will not be created if there are already duplicates in the collection. You can fix this (with extreme caution: DELETES data which is duplicate or null) using dropDups:true.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.