我想让前端知道是否存在验证问题,如重复提交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;