【问题标题】:castError Mongoose, cast to ObjectId failedcastError Mongoose,转换为 ObjectId 失败
【发布时间】:2021-03-14 15:22:48
【问题描述】:
app.get('/:id', async (req, res) => {
    const Id = req.params.id
    console.log(Id)
    console.log('Success');

    const properties = await Property.findOne({ _id: Id})
    if (properties== null) res.redirect('/home');

    res.render('property-single.ejs', { properties: properties});
})
app.get('/search', async (req, res) => {
    console.log('Search Success')
    
    try {
        const searchQuery = req.query.keyword
        const properties = await Property.find({ $or: [{name: {$regex: searchQuery, $options: 'i'}}, {desc: {$regex: searchQuery, $options: 'i'}}]})
        mongoose.Types.ObjectId(properties._id)
        
        res.render('property-grid.ejs', {properties: properties})
    } catch (err) {
    console.error(err);
    }
})

因此,当我删除 app.get('/:id) 时,底部的 app.get('/search') 工作正常,但是当我将其添加回来时,它返回一个错误提示

const castError = new CastError();
                    ^

CastError: Cast to ObjectId failed for value "search" at path "_id" for model "Property"`

这是我的架构

const propertySchema = new mongoose.Schema ({
    name: String,
    price: Number,
    jenis: String,
    lokasi: String,
    alamat: String,
    tipe: String,
    luas: Number,
    kt: Number,
    km: Number,
    carslot: Number,
    picture: String,
    desc: String,
})

之前谢谢!

【问题讨论】:

  • 你能退出Id吗?还有,为什么/search中的`mongoose.Types.ObjectId(properties._id)? _id`已经是一个ObjectId了。
  • 在 '/:id' 路由之前/上方定义你的 '/search' 路由。
  • 现在你对搜索路由的请求被 '/:id' 路由拦截,认为 'id' 参数的值是搜索。
  • @AlexanderStaroselsky 我的朋友告诉我这样做......我会改变它!
  • @NaveenChahar Woah 现在可以工作了!非常感谢先生!我真的不知道定义顺序会影响它

标签: javascript node.js mongodb mongoose ejs


【解决方案1】:

我很确定这种情况正在发生,因为 express 从 top of the file to the bottom 注册了它的路由。一个好的经验法则是将更“具体”的路线放在顶部,将较少的路线放在底部。

在这种情况下,您会收到错误消息,因为您认为您的路线正在到达 /search,而实际上它正在到达 /:id。如果您在文件中交换这些路由的顺序,事情应该会更可预测。

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2022-01-23
    • 2017-05-26
    • 2020-08-25
    • 2021-06-27
    • 2018-01-06
    • 1970-01-01
    • 2015-07-16
    • 2019-01-06
    相关资源
    最近更新 更多