Node.js – 如何用mongoose db创build一个唯一的id

我正在使用Twitter身份validation,并希望将twitter标识存储为mongodb中的唯一键。 但是,我看到多个条目具有相同的ID。 这是我的模式和代码

架构:

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

码:

  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); 

数据库shell输出

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

我的猜测是要么没有在MongoDB中创build索引,要么已经存在同名的索引。 如果它已经存在, ensureIndex将使用ensureIndex来创build它,但是如果它已经存在,它不会覆盖/重新定义它。 使用mongo js shell查看它是否存在,然后尝试删除它,重新启动mongod,然后再次运行node.js代码。

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