router.post('/', verifyToken, async (req, res) => {
const { jobCode, jobName } = req.body
//Validation for missing information
if (!jobCode || !jobName) {
return res.status(400).json({
success: false,
message: 'Please fill all the information!'
})
}
//Communicate with database
try {
//[VID]: Existing element
const job = await Job.findOne({ jobName })
if (job) {
return res.status(400).json({
success: false,
message: 'This job is existed'
})
}
//Passing all validation
const newJob = new Job({
jobCode,
jobName
})
await newJob.save()
res.json({
success: true,
message: 'Create new job successfully!',
job: newJob
})
} catch (error) {
console.log(error)
res.status(500).json({
success: false,
message: ' Internal server error'
})
}
})
This is my code to validate that to find the jobName in database and if it is existed, server will give a message 'This job is existed'. However, I have jobCode to check existance. So how can I add jobCode to check existence like jobName?
CodePudding user response:
jobCode AND jobName:
const job = await Job.findOne({ jobCode, jobName })
jobCode OR jobName:
const job = await Job.findOne({ $or: [{ jobCode }, { jobName }]});
CodePudding user response:
I think I have 2 ways for u
//Name
const jobName = await Job.findOne({ jobName })
if (jobName ) {
return res.status(400).json({
success: false,
message: 'This job is existed'
})
}
//Code
const jobCode = await Job.findOne({ jobCode })
if (jobCode ) {
return res.status(400).json({
success: false,
message: 'This job is existed'
})
}
Or
const job = await Job.findOne({ $or: [{ jobCode }, { jobName }]});
if (job) {
return res.status(400).json({
success: false,
message: 'This job is existed'
})
}