【发布时间】: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);
});
【问题讨论】: