Nodejs应用程序抛出E11000重复键错误

时间:2016-09-02 10:14:19

标签: javascript node.js mongodb express

当我在网页上输入数据时,数据会正确同步到数据库 但是,当我尝试再次填充相同的表格时,它会出错:

{
    "code": 11000,
    "index": 0,
    "errmsg": "E11000 duplicate key error collection: test.creates index: aname_1 dup key: { : \"MicroSoft\" }",
    "op": {
        "aname":"MicroSoft",
        "pname":"Bing",
        "pusername":"Debtanu",
        "_id":"57c9486d690a35fc21794169",
        "__v":0
    }
}

从DB中删除所有内容并再次尝试填写相同的表单后,将获取该条目 那为什么不将下一个条目带到同一个账户表格?

以下是我的app.js和Account.jade文件。

app.js:

var express = require('express');
 var favicon = require('serve-favicon');
 var path = require('path');
 var logger = require('morgan');
 var cookieParser = require('cookie-parser');
 bodyParser = require('body-parser');
 var session = require('express-session')
 var mongoose = require('mongoose');
 var nodemailer = require('nodemailer');
 var passport = require('passport');
 var LocalStrategy = require('passport-local').Strategy;
 var bcrypt = require('bcrypt-nodejs');
 var async = require('async');
 var crypto = require('crypto');
 var flash = require('express-flash');
 var router = express.Router();
 var fs = require('fs');


var createSchema = new mongoose.Schema({
    cname: {type: String, unique: true, sparse: true},
    aname : {type: String, unique: true, sparse: true},
    ausername : String,
    pname : {type: String, unique: true, sparse: true},
    pusername : String
});


var Create = mongoose.model('Create', createSchema);

mongoose.connect('localhost');

var app = express();


// Middleware
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
    secret:'keyboard cat',
    // connect-mongo session store
    proxy: true,
    resave: true,
    saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname,'/public')));
app.use('/img',express.static(path.join(__dirname, 'public/images')));




app.get('/Account', function(req, res) {
    res.render('Account', {
        user: req.user 
    });
});

app.post('/Account', function(req,res,next){
    var create = new Create({
        cname: req.body.cname,
        aname: req.body.aname,
        ausername: req.body.ausername
    });

    create.save(function(err, doc){
        if(err) res.json(err)
        else res.redirect('/home');
    });
});

// Server
app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

module.exports = app;

account.jade的格式不合适

1 个答案:

答案 0 :(得分:0)

由于您已在Schema中将aname声明为唯一字段,因此您只能在数据库中保存唯一值。这与cname和pusername相同。

在您的情况下,当您第一次保存MicroSoft时,它会保存文档。然而,在您下次尝试保存MicroSoft时,mongo会抛出错误,因为数据库中已存在相同的值。

因此,作为解决方案,您应该删除唯一条件,或者只保存唯一值。