猫鼬重复键错误处理和未处理的承诺拒绝

时间:2019-12-10 15:33:43

标签: node.js mongodb mongoose error-handling promise

我有一个遵循给定模式的用户模式。 根据目的,我让用户注册该站点,然后让他们更新其汽车和汽车编号。 车牌号必须是唯一的字符串,而名称可以是任何东西。

这是我的架构->

const mongoose = require('mongoose');
require('mongoose-type-email')

const Email = mongoose.Types.Email;
const Schema = mongoose.Schema;

var carNum = new Schema ({
    plateNum : {

        type : String,
        unique : true,
        sparse: true

    },
    name : {
        type : String
    },
    price : {
        type : Number
    }
});

var userSchema = new Schema({
    name : {
        type : String,
        required : true
    },
    email : {
        type : Email,
        required : true,
        unique : true
    },
    password : {
        type : String,
        required : true
    },
    car : [carNum]
});




var users = mongoose.model('user',userSchema);

module.exports = users;

这是处理插入的代码。

.post((req,res,next) =>{
    var plate = req.body.plateNum;
    var carname = req.body.carName;
    users.findOne({'_id': `${userId}`})
    .then((result) =>{
        res.statusCode = 200;
        res.setHeader('Content-type',"application/json");
        res.json(result)

        result.car.push({
            plateNum : plate,
            name : carname,
        })
        result.save()

    })
    .catch((err) => {
        console.log( "Error :    "+ err);
        res.send('The name plate number already exists')
    });  
})

当我尝试发送重复的或已经存在的铭牌时,它会返回未处理的承诺拒绝警告,并带有mongoDB错误。

UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: tarp.users index: car.plateNum_1 dup key: { car.plateNum: "asd" }
    at Function.create (C:\Users\Harsh Verma\Documents\VIT\TARP\Project\Tarp Project\node_modules\mongodb\lib\core\error.js:44:12)
    at toError (C:\Users\Harsh Verma\Documents\VIT\TARP\Project\Tarp Project\node_modules\mongodb\lib\utils.js:150:22)
    at coll.s.topology.update (C:\Users\Harsh Verma\Documents\VIT\TARP\Project\Tarp Project\node_modules\mongodb\lib\operations\common_functions.js:373:39)    
    at handler (C:\Users\Harsh Verma\Documents\VIT\TARP\Project\Tarp Project\node_modules\mongodb\lib\core\sdam\topology.js:1000:24)
    at wireProtocol.(anonymous function) (C:\Users\Harsh Verma\Documents\VIT\TARP\Project\Tarp Project\node_modules\mongodb\lib\core\sdam\server.js:457:5)     
    at C:\Users\Harsh Verma\Documents\VIT\TARP\Project\Tarp Project\node_modules\mongodb\lib\core\connection\pool.js:408:18
    at process._tickCallback (internal/process/next_tick.js:61:11)
(node:14348) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

我确实有.catch放在那里,所以那里缺少东西。

我想让用户知道盘子已经存在。

但是我确实设法使它起作用,但我不知道为什么这不是第一件事。

这是工作的东西

.post((req,res,next) =>{
    var plate = req.body.plateNum;
    var carname = req.body.carName;
    users.findOne({'_id': `${userId}`})
    .then((result) =>{
        res.statusCode = 200;
        res.setHeader('Content-type',"application/json");
        // res.send(result);
        result.car.push({
            plateNum : plate,
            name : carname,
        })

        result.save()
        .then((saved) => {
           // Nothing gets consoled
            console.log(saved)
        })
        .catch((err) => {

            console.log( "Error :    "+ err);
            res.send('The name already exists')
        });
    })
    .catch((err) => res.send('Unable to save : ' + err));  
})

1 个答案:

答案 0 :(得分:0)

第一个不起作用,因为Duplicate引发的.save()异常不是.findOne()引发的,并且一旦将catch块添加到save()中,它就可以工作

相关问题