在mongodb上输入重复数据时获取mongoose保存错误null

时间:2017-12-16 08:42:42

标签: node.js mongodb mongoose mongoose-schema

嗨,请帮我解决代码我有userSchema,用户名和密码都是唯一的。当我在MongoDB数据上输入重复数据时保存成功。我想在MongoDB中放入重复数据时出错。

//UserSchema

var userSchema =mongoose.Schema({
    user:{type:String,require:true,unique:true},
    pass:{type:String,require:true,unique:true}
})


router.post('/users',function(req,res){    
    var newUser = new Item.user({
        user:req.body.username,
        pass:req.body.password
    });        
    if(req.body.username ==null || req.body.username=='' || req.body.password ==null || req.body.password=='' ){            
        res.json({success : false, message : 'Ensure username ,email and password provided'});
    }else{
        newUser.save(function(err){
            console.log('save errror ',err);
            if(err){                     
                res.json({success : false , message :'user already exist' });
            }
            else{                    
                res.json({success :true , message : 'successfully saved'});
            }
        });

    }    
});

1 个答案:

答案 0 :(得分:1)

以下是执行所需操作的代码的最小工作示例。 请查看错误是如何处理的。因此,可以将重复键错误与任何其他错误分开。

我曾经使用expressbody-parsermongoose来使其发挥作用。还重构了一下你的代码。希望这会有所帮助。



const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

mongoose.connect('mongodb://localhost/my_database');

const UserSchema = mongoose.Schema({
    user: {type: String, require: true, unique: true},
    pass: {type: String, require: true, unique: true}
});

const User = mongoose.model('User', UserSchema);

const app = express();
app.use(bodyParser.json());

app.post('/users', function (req, res) {
    if (!req.body.username || !req.body.password) {
        res.json({success: false, message: 'Ensure username, email and password provided'});
        return;
    }

    const newUser = new User({
        user: req.body.username,
        pass: req.body.password
    });

    newUser.save(function (err) {
        if (err) {
            console.log('save errror ', err);

            if (err.name === 'MongoError' && err.code === 11000) {
                // Duplicate error happened. You can handle it separately.
                res.json({success: false, message: 'user already exist'});
                return;
            }

            // Some other error happened, you might also want to handle it.
            res.json({success: false, message: 'some error happened'});
            return;
        }

        res.json({success: true, message: 'successfully saved'});
    });
});

app.listen(8888);