I'm facing an issue where I know what the problem is, but can't wrap my head around why it's happening. In my simple recipe app that utilizes express and mongoose, users input recipe information through a form which is then saved to the database using mongoose methods. Everything seems to work smoothly as when I log test data, I can see that the following data is successfully saved:
{
ingredients: [ 'peanut butter', 'jelly', 'bread' ],
_id: 5e47d564f775ce247052d01c,
name: 'pb jelly sammich',
author: 'rob',
oneLiner: 'classic pb jelly sammich',
image: 'picofpbsammich here',
method: 'add all the ingredients together and boom! pb jelly sammich.',
__v: 0
}
(This is also visible when checking mongo db with db.recipes.find() and when passing the object to the ejs show template.
However, upon accessing my show route via a get request, I encounter a lengthy error message using the aforementioned test data. The crucial portion of the error message reads:
'Cast to ObjectId failed for value "picofpbsammich here" at path "_id" for model "Recipes"',
While I comprehend the issue at hand, I am perplexed by its occurrence. Here is my show route:
app.get("/recipes/:id", function (req, res) {
console.log(req.params.id)
Recipe.findById(req.params.id, function (err, foundRecipe) {
if (err) {
console.log(err);
} else {
res.render("show", { recipe: foundRecipe });
}
})
})
Logging req.params.id as shown above produces:
5e47d564f775ce247052d01c
picofpbsammich here
The first line contains the correct ID while the second line clearly does not and causes the problem. However, I am unable to pinpoint where this incorrect value is originating from. Why would req.params.id retrieve the VALUE of a property with a completely different name?
Since I am new to mongoose, I suspect it may be a minor mistake on my part. Any explanations would be greatly appreciated.
Here is the model being used:
var mongoose = require("mongoose");
let recipeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
author: String,
oneLiner: String,
ingredients: [String],
image: String,
method: String
})
module.exports = mongoose.model("Recipes", recipeSchema)