【问题标题】:MongoError: E11000 duplicate key error collection: timeformationBD.formations index: description_1 dup key: { : null } [duplicate]MongoError:E11000 重复键错误集合:timeformationBD.formations 索引:description_1 重复键:{:null } [重复]
【发布时间】:2019-01-05 09:46:02
【问题描述】:

你好,请任何人帮助我
执行 POST 操作时出现重复键错误 我尝试了几个来纠正它们,但我不明白发生了什么

错误 MongoError: E11000 重复键错误集合:timeformationBD.formations 索引:description_1 重复键:{ : null }

这是我的编队路线

 var express = require('express');
    var router = express.Router();
    var Formation = require('../models/formations');

    router.post('/', function(req, res){
        var newFormation = {
            name: req.body.name,
            position : req.body.position,
            department : req.body.department,
            salary: req.body.salary
        }
         Formation.addFormation(newFormation,function(err,formation){
             if(err) throw err;
             res.json(formation);
         });
     })

     module.exports = router

;

这是我的formation.models

var mongoose = require('mongoose');
var FormationSchema = new mongoose.Schema({
    name: String,
    position : String,
    department : String,
    salary : String
})

var Formation = module.exports = mongoose.model('Formation', FormationSchema);


module.exports.addFormation = function(newFormation, callback){
    Formation.create(newFormation, callback);
}

这是我的 app.js(端点)

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');

const User = require('./models/user');
const Formation = require('./models/formations');



mongoose.connect(config.database ,  { useNewUrlParser: true });
mongoose.connection.on('connected', () => {
console.log('connected to database... ' + config.database);
});

mongoose.connection.on('error', (err) => {
console.log('database error'+err);
});




/*mongoose.connect('mongodb://localhost:27017/hello', { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log('we are connected!');

});*/



const app = express();
const users = require('./routes/users');
const formations = require('./routes/formations');

//port number
 const port = 3001;

//cors middleware
 app.use(cors({
     origin: 'http://localhost:4200'
 }));
 //passwport middelware
 app.use(passport.initialize());
 app.use(passport.session());
 require('./config/passport')(passport); //pour implémenter fichier passport.js

 //set static folder
 app.use(express.static(path.join(__dirname + '/public')));




//BodyParser middleware
app.use(express.json());
app.use(bodyParser.json());
app.use('/users', users);//hedhiya ki nekteb /users barka f url yemchili direct lel const users = require('./routes/users'); fichier hedhka

app.use('/formations', formations); 

//c un route 
//just meloul 7atineha bch ntastiw beha 
//index route
 app.get('/', function(req, res){
    res.send('invalid endpoint');
});



//start Server
app.use(bodyParser.urlencoded({extended:true}));

 app.listen(port, () => {
    console.log('Server started on port' +port);
 });

【问题讨论】:

    标签: node.js web


    【解决方案1】:

    我认为您遇到的问题类似于以下帖子中描述的问题。

    https://www.opentechguides.com/askotg/question/16/mongodb-create-unique-index-e11000-duplicate-key-error-collection-dup-keynull.

    Answered By Sonja on opentechguides.com.
    
    When a new index is created, all existing documents must have one. If they don't, a null value is assigned.
    
    When you create a unique index there can be only one (or none) pre-existing document without that index.
    
    If there are multiple documents with that index missing, then index build fails. Null value cannot be assigned to more than one documents because of the unique constraint.
    
    Solution: Remove pre-existing documents without an index or assign unique values manually.
    

    您需要删除旧索引https://docs.mongodb.com/manual/reference/method/db.collection.dropIndex/,然后再次生成新索引。 https://docs.mongodb.com/manual/reference/method/db.collection.reIndex/

    我不确定为什么它没有首先分配索引。

    【讨论】:

    • 感谢您的帮助,当我再次重复所有粗略时,我解决了问题
    • @khouloudES ??
    • @khouloudES 如果我的回答对你有帮助,你能接受吗?
    猜你喜欢
    • 2018-07-29
    • 2020-05-11
    • 2021-09-02
    • 2023-03-25
    • 2018-07-21
    • 2021-07-25
    • 2021-10-01
    • 2019-09-10
    • 1970-01-01
    相关资源
    最近更新 更多