I’m working on a mock admin panel for a mock storefront using NextJS, Tailwind, MongoDB Atlas, and Mongoose. I’ve put together a document that holds my ‘GET’ code, ‘POST’ code, ‘PUT’ code, and ‘DELETE’ code. So far the GET, POST, and DELETE commands work; however, I’m unable to get the PUT command to work.
This is code from a previous project that I put together from a video series I found on YouTube…and it worked fine in that project
First, the document that holds my commands…
import { mongooseConnect } from "@/lib/mongoose";
import { Product } from "@/models/Product";
import { ObjectId } from "mongodb";
export default async function handle(req, res) {
// This will store the required properties
const { method } = req;
// This will connect to the database
await mongooseConnect();
// This will grab product(s) from the database
if (method === 'GET') {
if (req.query?.id) {
res.json(await Product.findOne({ _id: req.query.id }));
} else {
res.json(await Product.find());
}
//res.json(await Product.find());
}
// This will create a new product in the database
if (method === 'POST') {
const { title, description, price } = req.body;
const productDoc = await Product.create({
title, description, price
})
res.json(productDoc);
}
// This will update a product in the database
if (method === 'PUT') {
const {title,description,price,_id} = req.body;
var id = new ObjectId(_id);
console.log(id);
await Product.updateOne({id}, {title,description,price});
res.json(true);
}
// This will delete a product from the database
if (method === 'DELETE') {
if (req.query?.id) {
await Product.deleteOne({ _id: req.query?.id });
res.json(true);
}
}
}
The code that I utilized in the other project, for the PUT command, looked like this…
if (method === 'PUT') {
const {title,description,price,_id} = req.body;
await Product.updateOne({id}, {title,description,price});
res.json(true);
}
This didn’t work in this project and after some searching I found that ‘_id’ was trying to be used as a string; so, I changed the code a bit to make it an ObjectId…
Here is the document that handles the item…in this case a product…
import axios from "axios";
import Link from "next/link";
import { useRouter } from "next/router";
import { useState } from "react";
export default function ProductForm({
_id,
title: existingTitle,
description: existingDescription,
price: existingPrice,
}) {
// States
const [title, setTitle] = useState(existingTitle || "");
const [description, setDescription] = useState(existingDescription || "");
const [price, setPrice] = useState(existingPrice || "");
const [goToProducts, setGoToProducts] = useState(false);
const router = useRouter();
// Save product to the database
async function saveProduct(ev) {
ev.preventDefault();
const data = {
title,
description,
price,
};
if (_id) {
try {
// update
await axios.put("/api/products/", [{ ...data, _id }]);
} catch (error) {
console.log(error);
}
} else {
// create
await axios.post('/api/products', data);
}
// redirect back to product page
setGoToProducts(true);
}
if (goToProducts) {
router.push('/products');
}
return (
<form onSubmit={saveProduct}>
{/* Product Name */}
<label>Product Name</label>
<input
type="text"
placeholder="Product Name"
value={title}
onChange={(ev) => setTitle(ev.target.value)}
/>
{/* Product Category */}
{/* <label>Category</label> */}
{/* Product Description */}
<label>Product Description</label>
<textarea
type="text"
placeholder="Description"
value={description}
onChange={(ev) => setDescription(ev.target.value)}
></textarea>
{/* Product Price */}
<label>Price</label>
<input
type="number"
placeholder="Price"
value={price}
onChange={(ev) => setPrice(ev.target.value)}
/>
<div>
<button type="submit" className="btn-primary mr-5">
Save
</button>
<Link href={'/products'} type="button" className="btn-red text-xl tracking-wide">
Cancel
</Link>
</div>
</form>
)
}
And here is the code snippet that actually activates the different commands…
// Save product to the database
async function saveProduct(ev) {
ev.preventDefault();
const data = {
title,
description,
price,
};
if (_id) {
try {
// update
await axios.put("/api/products/", [{ ...data, _id }]);
} catch (error) {
console.log(error);
}
} else {
// create
await axios.post('/api/products', data);
}
// redirect back to product page
setGoToProducts(true);
}
As mentioned above I can get the POST, GET, and DELETE commands to work just fine.
I’ve tried converting the _id from a string to an ObjectId. Which was supposed to make MongoDB recognize it as an ID; however, this doesn’t seem to be the case as the product I’m trying to update is not updated.
I’ve added a console.log for _id in my api as follows…
// This will update a product in the database
if (method === 'PUT') {
const {title,description,price,_id} = req.body;
**console.log(req.body._id);**
var id = new ObjectId(_id);
**console.log(id);**
await Product.updateOne({id}, {title,description,price});
res.json(true);
}
…and I get the following output…
undefined,
new ObjectId(‘6673add4380496a134b753ea’)
Can someone please help me figure this out…I haven’t found anything online for this specific issue.
Also, if I’m missing anything, please let me know