I am trying to create a product update function for an ecommerce store, but the Product.findOneAndUpdate() keeps returning null.
const updateProduct = await Product.findOneAndUpdate({ id }, req.body, {
new: true,
});
here's my route:
const express = require('express');
const {
createProduct,
getaProduct,
getAllProducts,
updateProduct,
} = require('../controller/productCtrl');
const router = express.Router();
router.post('/', createProduct);
router.get('/:id', getaProduct);
router.get('/', getAllProducts);
router.put('/:id', updateProduct);
module.exports = router;
here's my product model:
const mongoose = require('mongoose'); // Erase if already required
// Declare the Schema of the Mongo model
var productSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
},
slug: {
type: String,
required: true,
unique: true,
lowercase: true,
},
description: {
type: String,
required: true,
unique: true,
},
price: {
type: Number,
required: true,
},
category: {
type: String,
required: true,
},
brand: {
type: String,
required: true,
},
quantity: {
type: Number,
required: true,
},
sold: {
type: Number,
default: 0,
},
images: {
type: Array,
},
color: {
type: String,
required: true,
},
ratings: [
{
star: Number,
postedby: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
},
],
},
{
timestamps: true,
}
);
//Export the model
module.exports = mongoose.model('Product', productSchema);
And here's my product control function for updating products. it returns null and i cant see why.
const Product = require('../models/productModel');
const asyncHandler = require('express-async-handler');
const slugify = require('slugify');
const updateProduct = asyncHandler(async (req, res) => {
const id = req.params;
try {
if (req.body.title) {
req.body.slug = slugify(req.body.title);
}
const updateProduct = await Product.findOneAndUpdate({ id }, req.body, {
new: true,
});
console.log(updateProduct);
res.json(updateProduct);
} catch (err) {
throw new Error(err);
}
});
module.exports = { createProduct, getaProduct, getAllProducts, updateProduct };
findOneAndUpdate should be like this using
_id