castError Mongoose,转换为ObjectId失败


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

谢谢!

我很确定这是因为express注册了从文件顶部到底部的路由。一个好的经验法则是让你的;特定的";顶部的路线和底部的较小路线。

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

相关内容

最新更新