我想让前端知道是否存在验证问题,如重复提交ID.我已经准备了许多堆栈帖子,并try 了此代码中的各种解决方案……

总之,没有一个catch方法会捕获错误.这就像mongo或mongoose在我的代码得到查看之前抛出它:(

以下是我的代码

exports.createFinishedJob = async (req, res) => {

    try {
        console.log('createFinishedJob req.body', req.body);
        const finishedjob = new FinishedJob();
        if (req.body.jobSubmissionId) { finishedjob.jobSubmissionId = req.body.jobSubmissionId };
        if (req.body.customerId) { finishedjob.customerId = new ObjectId(req.body.customerId) };
        finishedjob.finishedjob = req.body.finishedjob;
        if (req.body.other) { finishedjob.other = req.body.other };
        console.log('createFinishedJob', finishedjob);

        let error;
        try {
            await finishedjob.save()
                .catch(err => console.log("HALLO err", err));
            // if (res && doc) {
            //     return res.json(doc);
            // } else {
            //     return doc
            // }
        } catch (err) {
            error = err;
            console.log("createFinishedJob error", error)
        }
    } catch (err) {
        console.error("Something went wrong")
        console.error(err)

    }
};

以下是错误:-

(node:85241) UnhandledPromiseRejectionWarning: MongoServerError: E11000 duplicate key error collection: Genaich.processingjobs index: jobSubmissionId_1 dup key: { jobSubmissionId: "1006006" }
    at /Users/urfx/phos-code/genaich/node_modules/mongodb/lib/operations/insert.js:50:33
    at /Users/urfx/phos-code/genaich/node_modules/mongodb/lib/operations/command.js:84:64
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:85241) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

这是模型

const  mongoose  = require("mongoose");
const  Schema  =  mongoose.Schema;
const {ObjectId} = mongoose.Schema;
const SchemaTypes = mongoose.Schema.Types;
const  finishedjobSchema  =  new Schema(
    {
        customerId: { 
            type: ObjectId,
            ref: "User",
            required: false 
        },
        jobSubmissionId:{
            type: String, // if we don't get one from the customer use payment / order number
            unique: true,
            index: true
        },
        trashed: {
            type: Boolean
        },
        finishedjob: {
            type: Object
        },
        other: {
            type: SchemaTypes.Mixed // to start the ball rolling 
        }

    },
    { timestamps: true });

let  FinishedJob  =  mongoose.model("FinishedJob", finishedjobSchema);
module.exports  =  FinishedJob;

推荐答案

第一种 Select 是使用Model.create()方法,只捕获它抛出的任何错误.Model.create()就像const doc = new Model();+doc.save()在一个方法中.使用方法如下:

exports.createFinishedJob = async (req, res) => {
   try {
        // If this fails for any reason it will throw to the catch block
        const finishedjob = await FinishedJob.create({
            jobSubmissionId: req.body.jobSubmissionId,
            customerId: req.body.customerId,
            finishedjob: req.body.finishedjob,
            other: req.body.other
        });
        // This will only return if the document was created successfully
        return res.status(200).json({
            message: 'Job Created'
        });
    } catch (err) {
        console.error(err);
        // Check for the E11000 duplicate key error
        if(err.code === 11000){
            return res.status(400).json({
                message: err.message
            });
        }else{
            return res.status(500).json({
                message: 'Error on server'
            });
        }
    }
};

第二种 Select 是快速判断带有jobSubmissionIdFinishedjob是否已经存在,并提前返回错误消息.然而,如果没有匹配项,那么您仍然需要重新创建新文档,这意味着对数据库的两次调用,因此如果您每分钟处理对该路由的数千个新请求,则效率明显较低.使用方法如下:

exports.createFinishedJob = async (req, res) => {
    try {
        const existingFinishedjob = await FinishedJob.findOne({
           jobSubmissionId: req.body.jobSubmissionId
        });
        if (existingFinishedjob){
            return res.status(400).json({
                message: 'Already exists'
            });
        }
        const finishedjob = await FinishedJob.create({
            jobSubmissionId: req.body.jobSubmissionId,
            customerId: req.body.customerId,
            finishedjob: req.body.finishedjob,
            other: req.body.other
        });
        return res.status(200).json({
            message: 'Job Created'
        });
    } catch (err) {
        console.error(err);
        return res.status(500).json({
            message: 'Error on server'
        });
    }
};

Javascript相关问答推荐

当没有固定间隔时,是否可以在d3.js中进行画笔捕捉?

Vue.js使用特定索引值的数据更新html

Vue v模型检测父参考更改

未使用Outlet渲染子组件

导入图像与内联包含它们NextJS

使用ReactJS对Ant Design表中的空值进行排序

创建1:1比例元素,以另一个元素为中心

React存档iframe点击行为

使用useup时,React-Redux无法找到Redux上下文值

使用AJX发送表单后,$_Post看起来为空

按钮未放置在html dis位置

如何从html元素创建树 struct ?

你怎么看啦啦队的回应?

如何在每次单击按钮时重新加载HighChart/设置HighChart动画?

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

根据一个条件,如何从处理过的数组中移除一项并将其移动到另一个数组?

如何在HTMX提示符中设置默认值?

当从其他文件创建类实例时,为什么工作线程不工作?

如何组合Multer上传?

用另一个带有类名的div包装元素