Monsieur Zartosht

Monsieur Zartosht

Who am I?

A very simple blog that belongs to a very simple full-stack web developer about his daily life and struggles through coding. here you will find many things such as music, movies, and code (lots of codes!)

What I write about

Recent Posts

How to implement firstOrCreate in Mongoose

What if you wanted to check if something already existed in your mongo database and if it existed, return document and if not create one.

Table of contents

    Add custom methods to the mongoose

    For adding custom methods to mongoose in your model file (for example: models/Category.js) add this:

    CategorySchema.static("METHOD_NAME", callback)

    And you can call this method by invoking:


    Add firstOrCreate method

    Now that you learned how to add new method to your model, add the following:

    CategorySchema.static('firstOrCreate', async function (condition, document = {}) {
        return await this.findOne(condition).then(category => {
            if (!category) throw Error();
            return category;
        }).catch(error => {
            return this.create({...condition, ...document}).then(category => {
                return category
            }).catch(error => {

    In this method, we first look for the first document that matches the condition and if found, return it and if not create a new one with a combination of condition and document objects and return it. This function is async and for use it do the following:

        title: "test",
        url: ""
    }, {
        name: "test"
    }).then(response => {
    }).catch(error => {


    Now try to make a firstOrUpdate function and comment it below for me.

    Posted in Javascript , Mongo on by

    Share this post: