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

时间:2018-07-28 13:48:29

标签: node.js web

你好,请任何人帮助我
我在执行POST操作时收到重复的键错误 我尝试了几种方法来纠正它们,但我不知道发生了什么

错误 MongoError:E11000重复键错误集合:timeformationBD.formations索引:description_1 dup键:{: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

;

这是我的阵型。

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);
 });

1 个答案:

答案 0 :(得分:0)

我认为您遇到的问题与以下博文中所述类似。

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/

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