Error: Failed to convert string value "new" to an ObjectId at field "_id" in the "Model" model

I'm currently diving into Mongoose for a project in the Web Developer Bootcamp (the one on Udemy) and encountered an issue with it. It seems like a simple fix, but here are the Express routes included in index.js:

app.get('/products/new', (req, res) => {
    res.render('products/new', { categories });
});

app.post('/products', async (req, res) => {
    const newProduct = await new Product(req, body);
    await newProduct.save();
    res.redirect(`/products/${newProduct._id}`)
})

The other routes are working fine so I omitted them. Here is new.ejs:

<body>
    <h1>Add A Product</h1>
    <form action="/products" method="post">
        label for="name">Product Name</label>
        <input type="text" name="name" id="name" placeholder="product name">
        <label for="price">Price (Unit)</label>
        <input type="number" id="price" name="price" placeholder="price">
        <label for="category">Select Category</label>
        <select name="category" id="category">
            <% for(let category of categories){ %>
                <option value="<%=category%>">
                    <%=category%>
                </option>
                <% } %>
        </select>
        <button>Submit</button>
    </form>
</body>

When trying to access localhost:8080/products/new using the browser, this error pops up in the terminal:

/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/query.js:4719
  const castError = new CastError();
                    ^

CastError: Cast to ObjectId failed for value "new" (type string) at path "_id" for model "Product"
    at model.Query.exec (/home/christian-js/Code/MongoExpress/node_modules/mongoose/lib/query.js:4719:21)
    ...

Being new to Mongoose, I'm unsure how to proceed from here. If more information is needed, please let me know and I will update the question.

Answer №1

Here's a suggestion for you:

Consider trying the following code snippet: 
const createNewProduct = await new Product(req.body).save()
res.redirect(`/products/${createNewProduct._id}`)

It appears that there might be some issues with the arguments you're using while creating a new Product.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive Checkbox Generated in Jquery UI Accordion Header

I need help creating an accordion with checkboxes in the headers dynamically populated from a database. I have tried using the click() function to prevent the accordion from activating when checking the checkbox, but since the accordion is generated dynami ...

unexpected issue when trying to append a child element after creating its innerHTML

Upon executing this script, I expect to see the initially empty div with id="checkboxes" transformed into: <div id="checkboxes"> <label><input type="checkbox">option1</label> <label><input type="checkbox">opt ...

Angular Material Clock Picker for 24-Hour Time Selection

Struggling to find a time picker component that supports the 24-hour format for my Angular 14 and Material UI application. Can anyone help? ...

How can one effectively implement private methods in React JS for optimal performance?

When implementing a component or element callback for an event, tutorials and documentation typically provide code examples like this: 'use strict'; import React from 'react'; let FooComponent = React.createClass({ handleClick(args) ...

Looking to have two separate modules on a single page in AngularJS, each with its own unique view

<!DOCTYPE html> <html> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js" ...

Is there a way to use JavaScript to add content to a document and then facilitate the download of that document?

Is there a way in JavaScript to write content to a JSON or TXT file and then download it, similar to how it is done in Python? const content = "Hello"; const link = document.createElement('a'); link.setAttribute('download', 'FileTo ...

I'm currently in the process of building a brand new React.js application by utilizing the command "npx create-react-app". However, upon completion, I encounter an error while attempting to run it with the command "npm start"

Below is the complete error message Error message from ./src/index.js at line 1, character 58 Failed to parse module: Unexpected token found at (1:58) The following loaders were used to process the file: * ./node_modules/@pmmmwh/react-refresh-webpack-pl ...

Developing RESTful APIs with PDF as the primary source file

Can a PDF file be used as input for RESTful web services, and can a PNG image be sent as a response? If this is possible through REST services, kindly provide reference links on how to implement it. ...

Exploring ways to loop through a state array in React and strategically delaying each iteration based on conditions

Project: Currently, I am in the process of developing a Chatbot and my goal is to display the Chatbot messages sequentially with a delay between each message. Challenge: The messages are stored in a state array. Previously, I utilized map within the JSX o ...

What is the proper method for invoking a function when an HTTP request is made, whether it

Forgive me for asking what may seem like a silly question, but I am new to working with the backend. I am currently developing an AngularJS app using Express/Node and I am attempting to implement PayPal (using the Node.js SDK). My goal is to call the pay ...

Employing jQuery to populate information into an input field, yet encountering an issue where the data is not being successfully transmitted to

On my page, there is a form with an input box <input name="bid_price" id="bid_price" class="form-control"> If I manually enter a value, it gets posted successfully But when I try to insert a value using jQuery, it doesn't get posted, even tho ...

Learn how to showcase the URL path of an image stored in MongoDB on the front end of a website with the help of Node

I've managed to save the image paths of the uploaded pictures. They are stored like this http://localhost/public/Images/okro.jpg. However, I'm unsure how to retrieve them from the database and showcase them on the frontend. Is there a method to ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

The proper method to retrieve the parent function parameter within an inner JavaScript callback function

Consider the code snippet below. var exec = require('child_process').exec; var extraInfo = {'test':1,'passing':'test'}; runWithData(extraInfo); function runWithData(passedData) { exec('/Users/test/Deskto ...

Encountered a VUE error stating "Cannot use 'in' operator to search for 'path' in undefined". This issue led to an infinite loop, prompting me to search for solutions on StackOverflow and other similar forums. More details can be found

I am currently using this demo for learning purposes. If you want to see the full code, you can visit my GitHub repository here: https://github.com/tNhanDerivative/nhanStore_frontEnd and access my domain: vuestore.nhan-thenoobmaster.com. The error I am exp ...

Utilize jQuery to refresh the database with the information retrieved from the ajax-request

I am attempting to update the database. This is what I am doing From my JavaScript code var data = { "jobid": $('#jobid').val(), "names": $('#names').val(), "scripttype": $('#testscripts').val() }; var msg=""; f ...

Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller: public JsonResult GetRights(string ROLE_ID) { var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList(); return Json(re ...

Determining the victorious player in a game of Blackjack

After the player clicks "stand" in my blackjack game, my program checks for a winner. I am using AJAX to determine if there is a winner. If there is a winner, an alert will display their name. Otherwise, the dealer will proceed with making their move. Any ...

In the context of a controller, a directive with an isolate scope does not automatically update when a new element is added

I am currently working on implementing a basic recent searches list feature on my website. The idea is that when the user clicks on the search button, two inputs are combined and added to an array named "recentSearchItems". However, despite updating this a ...

Display loading spinner in Material-UI Table while fetching data

Is it possible to display a Circular progress indicator while waiting for data to populate the table? How can this be accomplished? Currently, the table shows No records to display until the data is retrieved from the server. https://i.stack.imgur.com/Ljq ...