猫鼬强制转换为ObjectID值失败...但是为什么

时间:2020-02-15 11:48:52

标签: javascript mongodb express mongoose

我知道问题出在哪里,但不知道为什么会这样。我有一个使用Express和猫鼬的简单食谱应用程序。用户通过表格传递配方信息,并通过猫鼬方法保存到数据库。这部分似乎工作正常,当我使用测试数据进行console.log时,我看到保存了以下数据:

{
  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
}

(这也是我使用db.recipes.find()检查mongo db时显示的内容,也是将对象传递给我的ejs show模板时显示的内容。

但是,当我通过get请求访问我的显示路线时,使用上述测试数据会收到一长串错误消息。这是错误消息的关键部分:

'Cast to ObjectId failed for value "picofpbsammich here" at path "_id" for model "Recipes"',

我理解问题出在哪里,但是对为什么会发生这种情况感到困惑。这是我的表演路线:

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 });
        }
    })
})

控制台如上所述记录req.params.id,打印以下内容:

5e47d564f775ce247052d01c
picofpbsammich here

第一行是正确的ID,第二行显然不是问题的原因,但是我不知道那可能是从哪里来的:S为什么req.params.id会提取属性的值那叫完全不同的东西?

我是猫鼬的新手,所以我做的事可能很愚蠢,任何解释都值得赞赏。

这是模型:

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)

1 个答案:

答案 0 :(得分:0)

您发布了以下代码:

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 });
        }
    })
})

您提到在console.log中收到:

5e47d564f775ce247052d01c
picofpbsammich here

接着记录异常:

'在路径“ _id”上对值“ picofpbsammich here”的对象ID投射失败 对于模型“食谱””,

从逻辑上让我假设您正在发出两个请求,其中一个是ID无效:

picofpbsammich here

猫鼬无法将此值转换为ObjectId,因此会得到异常,这在imo中是有意义的。