Having trouble updating information in my MongoDB Atlas Database using NextJS

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

New contributor

jcroft0827 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật