2017-06-12 58 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。 –