【问题标题】:I am getting duplicate key error -- MongoError: E11000 duplicate key error collection. I do have 2 collections, user and profile.我收到重复键错误 - MongoError:E11000 重复键错误集合。我确实有 2 个集合,用户和个人资料。
【发布时间】:2018-08-09 19:08:54
【问题描述】:

我正在尝试制作一个应该具有以下流程的项目。 注册 -> 登录 -> 个人资料创建 -> 秘密页面 我已经实现了注册和登录路由,但是当我为个人资料页面保存数据时,它显示了上述错误。我只能第一次保存数据。我也无法为其他用户保存数据。谢谢。

// This is the route which i am including.

    var express                 = require('express');
    var router                     = express.Router();
    var passport                 = require('passport');
    var multer                     = require('multer');
    var mongoose                 = require('mongoose');
    var User                     = require('../models/user.model.js');
    var Profile                 = require('../models/profile.model.js');
    var path                     = require('path');

// Defining the storage path to the multer    
    var storage = multer.diskStorage({
    destination : 'uploads/',
    filename: function(req, file, cb){
    cb(null, file.filedname + '-' +Date.now() + path.extname(file.originalname));
    },
    fileFilter: function(file, cb){
    checkFileType(file, cb);
    }
    });

// 
    var upload = multer({
    storage: storage
    });


//The signup route to post the username and password and register in the database
    router.post('/signup', function(req, res){
    req.body.username
    req.body.password
    User.register(new User({username : req.body.username}), req.body.password, function(err, user){
    if (err) {
    console.log(err);
    return res.render('signup.ejs');
    } 
    passport.authenticate('local')(req, res, function(){
    res.render('profile.ejs');
    });
    });
    });


// The login route to post the username and password and login into the portal
    router.post('/login', passport.authenticate('local', {
    successRedirect : '/secret',
    failureRedirect : '/login'
    }), function (req, res) {

// body...
// console.log("Login Working");
    });

// The profile route to render the profile page only if logged in
    router.get('/profile', isLoggedIn, function(req, res){
    res.render('profile.ejs')
    });

// The profile route. This route is generating error        
    router.post('/profile', upload.any(), function(req, res){
    console.log(req.body);
    var profileDetails = {};
    profileDetails.path = req.files[0].path;
    profileDetails.originalname = req.files[0].originalname;
    profileDetails.name = req.body.profileName;
    profileDetails.email = req.body.profileEmail;
    Profile.create(profileDetails, function(err){
    if (err) {
    console.log(err);
    }
    res.redirect('/missing');
    });
    });

    router.get('/missing', isLoggedIn, function (req, res) {
// body...
    res.render('missing.ejs')
    })

//The function to check is user is logged in or not
    function isLoggedIn(req, res, next){
    if (req.isAuthenticated()) {
    return next();
    }
    res.redirect('/login');
    }

    module.exports = router;

【问题讨论】:

  • 你能发布完整的错误信息吗?很难说它抱怨的是哪个键。
  • { MongoError: E11000 duplicate key error collection: demo-db.profiles index: username_1 dup key: { : null } at Function.MongoError.create (E:\Demo\V5\node_modules\mongodb- core\lib\error.js:49:10) 在 toError (E:\Demo\V5\node_modules\mongodb\lib\utils.js:149:22) 在 coll.s.topology.insert (E:\Demo\ V5\node_modules\mongodb\lib\operations\collection_ops.js:803:39) 在 E:\Demo\V5\node_modules\mongodb-core\lib\connection\pool.js:531:18 在 process._tickCallback (internal/进程/next_tick.js:61:11)
  • 您正在使用相同的用户名创建文档..

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您收到的错误消息是说已经有一个值为null 的用户名。这意味着已经有一个用户没有用户名,而您正在尝试添加另一个用户。

Mongo 文档对这些情况进行了如下说明:

如果文档在唯一索引中没有索引字段的值,则索引将存储该文档的空值。由于唯一性约束,MongoDB 将只允许一个缺少索引字段的文档。如果有多个文档没有索引字段的值或缺少索引字段,则索引构建将失败并出现重复键错误。

可以结合唯一约束和稀疏索引来过滤 这些空值来自唯一索引并避免错误。

您需要在注册用户时验证是否有真实用户名,或者您需要将sparse index 添加到集合中。 (它允许您输入多个具有空值的条目,但只会返回具有正确值的条目)。

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 2018-07-29
    • 2019-01-05
    • 2019-09-10
    • 2023-03-25
    • 2020-05-11
    • 2021-07-25
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多