【发布时间】:2020-07-20 08:09:48
【问题描述】:
我已经完成了很多研究,以找到我的问题的答案,但我没有发现任何东西。如果我错过了答案,请随时附上链接。
我确实找到了这个解决方案,但我并不完全确定它可能适用于这种情况:E11000 duplicate key error index in mongodb mongoose
我正在尝试将我的 Express.js、MongoDB、Passport.js 应用程序连接到 Mongo-Atlas。我有我的atlas群集设置并接受来自我的localhost的新用户,并使用Google OAuth 2.0,但是,当我尝试使用Facebook注册或登录时,我收到以下错误。
MongoError: E11000 duplicate key error collection: userDB.users index: username_1 dup key: { username: null }
会不会跟这个有关?
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
它在连接到我的localhost mongodb时工作,正如我所说,我发现了找到解决方案。
passport.use(new FacebookStrategy({
clientID: process.env.FBAPPID,
clientSecret: process.env.FBSECRET,
callbackURL: "http://localhost:3000/auth/facebook/secrets"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ facebookId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/secrets',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/secrets');
});
更新
所以我发现了一些关于删除索引的文档MongoDB但是这不完全清楚,所以我还发现了一篇文章Dropping Existing Indexes所以我将代码实现为自己的app.js文件。 p >// Dropping an Index in MongoDB
User.collection.dropIndex({name : "username_1"}, function(err, res) {
if (err) {
console.log('Error in dropping index!', err);
}
});
我一直在测试之间丢弃数据库,看看是否有效,但是我一直抛出这个错误一切,无论我如何改变代码,尝试解决它!
{ _bsontype: 'Timestamp', low_: 1, high_: 1586408833 },
ok: 0,
errmsg: `can't find index with key: { name: "username_1" }`,
code: 27,
codeName: 'IndexNotFound',
'$clusterTime': {
clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1586408833 },
signature: { hash: [Binary], keyId: [Long] }
},
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
}
然而,当我在连接到我的 Atlas 服务器的 Mongo Shell 中运行 db.users.getIndexes() 时。果然有!我什至尝试使用dropIndexes,它只删除了电子邮件索引!我对此感到非常沮丧!
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "userDB.users"
},
{
"v" : 2,
"key" : {
"email" : 1
},
"name" : "email_1",
"ns" : "userDB.users",
"background" : true
},
{
"v" : 2,
"unique" : true,
"key" : {
"username" : 1
},
"name" : "username_1",
"ns" : "userDB.users",
"background" : true
}
]
【问题讨论】:
-
我唯一可以提出解决问题的事情是在使用Facebook创建用户时将用户名设置为“无”。这似乎不是最好的解决方案。我仍然想知道是否有更好的选择。
-
所以 username: "none" 实际上并没有解决任何问题。我现在不知所措! :(
标签: node.js mongodb mongoose passport.js mongodb-atlas