Search code examples
node.jsmongodbmongoosemongoose-schema

Prevent Node JS application to crash if it encounters an error in the Mongoose Schema


Node JS application crashes whenever there is a error. I would like the application to prevent from crashing if it encounters an error. The Errors are shown as intended/designed, however, I would like my server to not crash. I am stuck and unsure how to proceed.

e.g if the title is empty, an error is raised as it is not within the characters set. (which is correct, however, I'd like my application to still be running and not to crash)

app.post('/createNote', async (req, res) => {

    const title = req.body.title
    const category = req.body.category
    const message = req.body.message

    try{
        const note =  new Note({ title: title, category: category, message: message })
        note.save()

        res.status(200).send('Note created')
    }   catch(err) {

        res.status(500).send(err)
    }

})
const NoteSchema = new mongoose.Schema({

    title: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50,
    },

    category: {
        type: String,
        enum: [
                'animals', 'career', 'connections'
            ],
        required: true
    },

    message: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 1000
    },



})

module.exports = mongoose.model('Note', NoteSchema, "Notes")

The code itself works, I can add notes without any issues, however when i encounter an error, my Node JS application crashes. I would like the "catch" to prevent that from happening and send the error to the client


Solution

  • You can try with

    await note.save()
    

    To get it caught in try catch.

    Please find mongoose doc on this topic here.

    In a general way you should catch all the error and do something with it, if your app crash that means there is a piece of code you do not manage.

    Yous can use tools like pm2 to restart the server automatically, but the better way is to anticipate errors and use them in your code logic.