【发布时间】: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