OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Having trouble updating information in my MongoDB Atlas Database using NextJS

  • Thread starter Thread starter jcroft0827
  • Start date Start date
J

jcroft0827

Guest
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...

Code:
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...

Code:
    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...

Code:
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=<p>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.
<strong>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</strong></p>
<p>First, the document that holds my commands...</p>
<pre><code>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);
        }
    }
}
</code></pre>
<p>The code that I utilized in the other project, for the PUT command, looked like this...</p>
<pre><code>    if (method === 'PUT') {
        const {title,description,price,_id} = req.body;
        await Product.updateOne({id}, {title,description,price});
        res.json(true);
    }
</code></pre>
<p>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...</p>
<p>Here is the document that handles the item...in this case a product...</p>
<pre><code>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>
    )
}
</code></pre>
<p>And here is the code snippet that actually activates the different commands...</p>
<pre><code> // 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);
    }
</code></pre>
<p>As mentioned above I can get the POST, GET, and DELETE commands to work just fine.</p>
<p>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...</p>
<pre><code>    // 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);
    }
</code></pre>
<p>...and I get the following output...
undefined,
new ObjectId('6673add4380496a134b753ea')</p>
<p>Can someone please help me figure this out...I haven't found anything online for this specific issue.
<strong>Also, if I'm missing anything, please let me know</strong></p>
                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...

Code:
 // 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...

Code:
    // 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

<p>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.
<strong>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</strong></p>
<p>First, the document that holds my commands...</p>
<pre><code>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);
}
}
}
</code></pre>
<p>The code that I utilized in the other project, for the PUT command, looked like this...</p>
<pre><code> if (method === 'PUT') {
const {title,description,price,_id} = req.body;
await Product.updateOne({id}, {title,description,price});
res.json(true);
}
</code></pre>
<p>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...</p>
<p>Here is the document that handles the item...in this case a product...</p>
<pre><code>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>
)
}
</code></pre>
<p>And here is the code snippet that actually activates the different commands...</p>
<pre><code> // 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);
}
</code></pre>
<p>As mentioned above I can get the POST, GET, and DELETE commands to work just fine.</p>
<p>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...</p>
<pre><code> // 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);
}
</code></pre>
<p>...and I get the following output...
undefined,
new ObjectId('6673add4380496a134b753ea')</p>
<p>Can someone please help me figure this out...I haven't found anything online for this specific issue.
<strong>Also, if I'm missing anything, please let me know</strong></p>
 

Latest posts

Online statistics

Members online
0
Guests online
2
Total visitors
2
Ads by Eonads
Top