【问题标题】:I keep get this error: MongoServerError: E11000我不断收到此错误: MongoServerError: E11000
【发布时间】:2021-11-06 14:09:12
【问题描述】:

我正在尝试使用护照和 mongodb 进行用户身份验证,但我不断收到错误消息。我尝试重新启动服务器并寻找放置等待功能的地方,但我相信我已经覆盖了所有的轨道。我仍然收到错误,我不知道为什么。它可能在数据库本身中,但我不确定,因为我是 mongodb 的新手

错误:

app: authRouter MongoServerError: E11000 duplicate key error collection: mernpractice.users index: email_1 dup key: { email: null }
  app: authRouter     at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\operations\insert.js:51:33
  app: authRouter     at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
  app: authRouter     at handleOperationResult (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\sdam\server.js:363:9)
  app: authRouter     at MessageStream.messageHandler (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection.js:479:9)
  app: authRouter     at MessageStream.emit (events.js:400:28)
  app: authRouter     at processIncomingData (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
  app: authRouter     at MessageStream._write (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
  app: authRouter     at writeOrBuffer (internal/streams/writable.js:358:12)
  app: authRouter     at MessageStream.Writable.write (internal/streams/writable.js:303:10)
  app: authRouter     at TLSSocket.ondata (internal/streams/readable.js:726:22) +0ms
(node:484) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'close' of undefined
    at addUser (C:\Users\Yanki XXIV\Desktop\pluralsight\src\routers\authRouter.js:29:16)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:484) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:484) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  app: authRouter MongoServerError: E11000 duplicate key error collection: mernpractice.users index: email_1 dup key: { email: null }
  app: authRouter     at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\operations\insert.js:51:33
  app: authRouter     at C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
  app: authRouter     at handleOperationResult (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\sdam\server.js:363:9)
  app: authRouter     at MessageStream.messageHandler (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\connection.js:479:9)
  app: authRouter     at MessageStream.emit (events.js:400:28)
  app: authRouter     at processIncomingData (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
  app: authRouter     at MessageStream._write (C:\Users\Yanki XXIV\Desktop\pluralsight\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
  app: authRouter     at writeOrBuffer (internal/streams/writable.js:358:12)
  app: authRouter     at MessageStream.Writable.write (internal/streams/writable.js:303:10)
  app: authRouter     at TLSSocket.ondata (internal/streams/readable.js:726:22) +9s
(node:484) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'close' of undefined
    at addUser (C:\Users\Yanki XXIV\Desktop\pluralsight\src\routers\authRouter.js:29:16)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:484) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

auth.js

const express = require('express');
const debug = require('debug')('app: authRouter');
const { MongoClient } = require('mongodb');

const authRouter = express.Router();

authRouter.route('/signUp').post((req, res) => {
    const {username, password} = req.body;
    const url = 
    'mongodb+srv://Yoshi:Yumcmaster1@cluster0.atic5.mongodb.net?retryWrites=true&w=majority'
    const dbName = 'mernpractice';

    (async function addUser(){
        let client
        try {
          let client = await MongoClient.connect(url);
            
          const db = client.db(dbName);
          const user = {username, password};
          const results = await db.collection('users').insertOne(user);
          debug(results);
          req.login(results.ops[0], ()=> {
            res.redirect('/auth/profile');
          });

        } catch (error) {
          debug(error)
        }
        client.close();
    }());

});
authRouter.route('/profile').get((req, res) => {
    res.json(req.user);
})

module.exports = authRouter;

app.js

const express = require('express');
const chalk = require('chalk');
const debug = require('debug')('app');
const morgan = require('morgan');
const path = require('path');
const passport = require('passport');
const cookieParser = require('cookie-parser');
const session = require('express-session');

const PORT = process.env.PORT || 3000;
const app = express();
const sessionsRouter = require('./src/routers/sessionsRouter');
const adminRouter = require('./src/routers/adminRouter');
const authRouter = require('./src/routers/authRouter');

app.use(morgan('tiny'));
app.use(express.static(path.join(__dirname, '/public/')));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieparser());
app.use(session({secret: 'globomantics'}));

require('./src/config/passport.js')(app)


app.set('views', './src/views')
app.set('view engine', 'ejs')

app.use('/sessions', sessionsRouter);
app.use('/admin', adminRouter);
app.use('/auth', authRouter);

app.get('/', (req, res) => {
    res.render('index', { title: 'Globomantics', data: ['a','b','c'] });
});

app.listen(PORT, () => {
    debug(`listening on port ${chalk.green(PORT)}`);
});

【问题讨论】:

    标签: node.js mongodb express authentication


    【解决方案1】:

    错误“E11000 重复键错误索引:...”是由于数据库中的数据错误,您需要清理集合 mernpractice.users 中的数据,因为有多个电子邮件丢失/空的记录并且您有唯一索引在电子邮件中。

    您可以使用查询获取所有丢失的电子邮件:

    db.users.find({
      email: {
        $exists: false
      }
    })
    

    db.collection.find({
      email: null
    })
    

    您需要清除所有电子邮件为空的文档或为查询返回的所有此类文档设置唯一电子邮件。

    此外,当您插入新记录时,您需要确保电子邮件可用,否则它将插入第一个带有 null 的记录,但所有后续插入都会尝试将电子邮件插入为 null 并引发相同的错误。

    请参考https://www.mongodb.com/community/forums/t/e11000-duplicate-key-error-collection/14141https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field

    【讨论】:

    • 我把这个放在哪里?我尝试将它放在 auth.js 中,在 authRouter.route 函数中,但它不起作用。
    【解决方案2】:

    对我来说,这是因为我将架构中的电子邮件字段设置为唯一。我创建了一个文档并将电子邮件的值设置为“exampleemail@example.com”。当我尝试创建/更新电子邮件值与上述相同的新文档时出现问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多