2017-06-12 79 views
1

我正在使用sessionstore npm模块将会话数据存储在数据库中。快速会话存储:MongoError:在_id上的E11000重复密钥错误集合

var session = require('express-session'); 
var sessionstore = require('sessionstore'); 

app.use(session({ 
    secret:appConfig.JWT_SECRET, 
    resave:false, 
    saveUninitialized:true, 
    store: sessionstore.createSessionStore({ 
     type: 'mongodb', 
     host: 'localhost', 
     port: 27017, 
     dbName: 'MyDatabase', 
     collectionName: 'sessions', 
     timeout: 10000 
    }), 
    cookie: { 
     maxAge: 1000 * 60 * 60 // Milliseconds (3600000ms -> 60min) 
    } 
})); 

,我收到此错误:

MongoError: E11000 duplicate key error collection: myDatabase.sessions index: _id_ dup key: { : "Lz4SJIHaBfGFfNg3_ChNTkFnwKBLQDUN" } 
    at Function.MongoError.create (/home/user/public_html/projectName/server/node_modules/mongodb-core/lib/error.js:31:11) 
    at toError (/home/user/public_html/projectName/server/node_modules/mongodb/lib/utils.js:139:22) 
    at /home/user/public_html/projectName/server/node_modules/mongodb/lib/collection.js:1060:67 
    at /home/user/public_html/projectName/server/node_modules/mongodb-core/lib/connection/pool.js:461:18 
    at _combinedTickCallback (internal/process/next_tick.js:73:7) 
    at process._tickDomainCallback (internal/process/next_tick.js:128:9) 

如何防止创建具有相同的身份证件。另外我不在我的项目中使用Mongoose。可以做什么,因为这不会使服务器崩溃,而是关闭与数据库的所有连接,并且用户无法登录(或者没有api响应)。

我也检查了一些关于SO和github的类似问题,但他们都指向猫鼬或字段名称的改变,但在我的情况下没有这样的事情。

请帮忙。

+0

看起来像一个bug。你有没有尝试设置另一个字段用于除_id之外的其他字段?请注意,在更改任何内容之前,您需要清除集合的内容。 –

+0

'db.sessions.drop()'是否工作? (从这个旧问题:https://github.com/jdesboeufs/connect-mongo/issues/78) – Lissy

+0

我没有添加任何其他密钥。我正在保存用户名和电子邮件地址是数据对象 –

回答

0

只要不指定ID,Mongo会自动为它分配一个未使用的ID。

db.collection.insert documentation,这种提取物从id section

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.

+0

阅读问题。这是由中间件插件完成的,而不是OP的代码。 Google未能回答这个问题。 –

+1

我没有添加任何_id。 –