I have following schema
const schema = new Schema(
{
ImageId: { type: String, ref: models.IMAGES },
reportedBy:[
userId:{type:String, ref: models.USER}
]
}
);
class ImageReport {}
schema.loadClass(ImageReport);
module.exports = model(models.IMAGEREPORT, schema);
And following code
reportImage: async (req, res, next) => {
try {
const { ImageId } = req.params;
const image = await Image.findOne({ ImageId }); // there is an image schema with fields: ImageId and url
if(!image)
return res.status(400).send({
statusCode: 400,
error:"CANNOT FIND THE IMAGE",
data: {},
});
const userId = "some userId";
try{
let imageReports = await ImageReport.findOne({ ImageId:ImageId})
if(imageReports){
imageReports.reportedBy.forEach(rep=>{
if(rep.userId===userId)
// this error should be returned immediately. Instead it goes to ImageReport.updateOne() call
return res.status(400).send({
statusCode: 400,
error: "YOU HAVE ALREADY REPORTED THIS IMAGE",
data: {},
});
});
}
} catch(err){
return res.status(400).send({
statusCode: 400,
error: error,
data: {},
});;
}
// this is called even if the error is found in the above try catch block
await ImageReport.updateOne(
{ImageId:ImageId},
{
$push:{
reportedBy:userId
}
},
{upsert:true},
function (error) {
if (error) {
return res.status(400).send({
statusCode: 400,
error: error,
data: {},
});
}
}
)
return res.status(200).send({
statusCode: 200,
error: 'THE IMAGE WAS REPORTED SUCCESSFULLY',
data: {},
});
} catch (e) {
return res.status(400).send({
statusCode: 400,
error: error,
data: {},
});
}
},
When i run this query and suppose the user already reported the image (i.e., their userId is in the 'reportedBy' array) the API call doesn't return error asap. instead it goes to the ImageReport.updateOne() call and inserts the document and then returns the error saying("YOU HAVE ALREADY REPORTED THIS IMAGE")
Can anyone tell me why isn't async await working properly? I am getting following error too
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: 1)
(node:16920) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.