How to check and create documents in MongoDB using Mongoose in Node.js

I’m having trouble with MongoDB operations in Node.js

I’m pretty new to working with MongoDB and Node.js. I need to verify if a Product document exists in my database, and if it doesn’t exist, I want to create a new one.

Here’s my Product schema setup:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    title: String,
    dateAdded: { type: Date, default: Date.now },
}, {collection: 'Products'})

const Product = mongoose.model('Product', ProductSchema);

For checking if a product exists, I wrote this function:

async function checkProductExists(productTitle, cb) {
    if(productTitle){
        Product.findOne({title: productTitle}, function(error, result){
            if(error){
                cb(error, null);
                console.log('Failed to find product: ' + productTitle)
            } else {
                cb(null, result.title);
            } 
        });
    }
}

And here’s my function to create a new product:

async function createProduct(productTitle, cb){
    if(productTitle){
        const newProduct = new Product({title: productTitle})

        await newProduct.save(function(error, savedProduct){
            if(error){
                cb(error, null);
                console.log('Failed to save product: ' + productTitle)
            } 
        })
    }
}

Both functions don’t seem to work properly. My MongoDB Atlas connection is working fine though. I’m using this connection string format:

mongodb+srv://user:pass@cluster.xyz123.mongodb.net/?retryWrites=true&w=majority

What could be wrong with my code? Are these methods written correctly?

your callback’s broken - you’re not calling cb() when createProduct succeeds. also, Mongoose dropped callback support after v6, so just use async/await. try const result = await Product.findOne({title: productTitle}) instead of mixing different patterns.

you’re mixing callback patterns with async/await - that’s probably what’s causing the weirdness. also, checkProductExists will crash if result comes back null. what happens when the product doesn’t exist? try using findOrCreate instead of separate functions.