Vinoth
Vinoth

Reputation: 5785

Node.js - How to create a unique id with mongoose db

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") }

Upvotes: 3

Views: 8266

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146164

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

Upvotes: 1

Related Questions