I am developing a REST service using Nodejs, Express, Mongoose. I'm still in the learning phase.
I have one question.
For example, when I try to pull content with an ID, if the ID is correct and corresponds, it works without any problems. But if the ID is incorrect or missing or more than 24 characters, the problem is that the service crashes. If a 24-character ID is received, I can return 404 and the service does not crash. How can I avoid this crashing issue.
Correct request (Returning result as JSON): http://localhost:8080/api/v1/posts?id=615ccb9f89a5e20454306090
Crash request: http://localhost:8080/api/v1/posts?id=123
Error:
events.js:366
throw err; // Unhandled 'error' event
^
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ status: 500, error: 'Post not found' })
at Function.emit (events.js:364:17)
at D:\CMS\node_modules\mongoose\lib\model.js:4872:15
at processTicksAndRejections (internal/process/task_queues.js:77:11) {
code: 'ERR_UNHANDLED_ERROR',
context: { status: 500, error: 'Post not found' }
}
[nodemon] app crashed - waiting for file changes before starting...
Controller layer:
...
function get(req, res) {
postService
.get(req)
.then((result) => result && res.status(200).json(result))
.catch((e) => errorMessages(e, res));
}
Service layer:
...
async function get(req) {
const findParams = {};
if (req.query.id) {
findParams['_id'] = req.query.id.trim().substring(0, 24);
}
const post = await Posts.find(findParams, (e, post) => {
if (e) throw { status: 500, error: `Post not found` };
return post;
}).sort({ createdDate: -1 });
if (req.query.id && post[0]) {
return { ...post[0]._doc };
}
return post;
}
Post Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
title: { type: String, unique: true, required: true, minlength: 1, maxlength: 64 },
meta: {
lang: { type: String, minlength: 2, maxlength: 2, default: 'en' },
distribution: { type: String, minlength: 1, maxlength: 64, default: 'global' },
robots: { type: String, minlength: 1, maxlength: 64, default: 'index,follow' },
author: { type: String, minlength: 1, maxlength: 64 },
description: { type: String, minlength: 1, maxlength: 256 },
keywords: { type: String, minlength: 1, maxlength: 256 },
canonical: { type: String, minlength: 1, maxlength: 512 },
others: { type: [Schema.Types.Mixed], default: [] },
},
coverImage: { type: String, minlength: 1, maxlength: 1024 },
summary: { type: String, required: true, minlength: 1, maxlength: 1024 },
body: { type: [Schema.Types.Mixed], default: [] },
slug: { type: String, unique: true, required: true, minlength: 1, maxlength: 1024 },
createdDate: { type: Date, required: true, default: Date.now },
status: { type: Boolean, required: true, default: true },
categories: [{ type: String, minlength: 1, maxlength: 32 }],
like: { type: Number, default: 0 },
dislike: { type: Number, default: 0 },
});
module.exports = mongoose.model('Posts', schema);
How can I prevent the service from crashing or is there a code I need to fix? Thanks.
CodePudding user response:
You can check if the provided string is a valid MongoDB ID before sending the query:
var ObjectId = require('mongoose').Types.ObjectId;
async function get(req) {
if (!ObjectId.isValid(req.query.id)){
throw { status: 400, error: `Invalid ID` }
}
...
}
CodePudding user response:
const post = await Posts.find(findParams, (e, post) => {
if (e) throw { status: 500, error: `Post not found` };
return post;
}).sort({ createdDate: -1 });
This is weird. If you are using await, then don’t pass callbacks. Just try/catch around this, which would have caught the error.