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?