【发布时间】:2018-07-19 00:46:12
【问题描述】:
我有一个userSchema 我必须用搜索关键字在用户记录中搜索
//userSchema
const userSchema = new Schema(
{
name: String,
city: String,
postalCode: Number
},
{
timestamps: true
}
);
所以 API 路由是localhost:3000/api/v1/search/:key 键可以是用户名或城市或邮政编码,根据我们必须从集合中获取结果的键。
这是我尝试过的userController
index: async (req, res, next) => {
const searchKey = req.params.key;
const searchResult = await User.find({
$or:[{name: searchKey},{city: searchKey},{postalCode: searchKey}]
});
res.status(200).json({
message: 'query was succesfull',
data: searchResult
});
}
如果我将 :key 传递为 加拿大,我会收到以下错误。如果我将 :key 传递为 123456 这是邮政编码,我正在获取数据
{
"error": {
"message": "Cast to number failed for value \"Canada\" at path \"postalCode\" for model \"users\""
}
}
那么我如何使这个查询更加健壮,以便基于:key 我必须从用户模型中获取数据
寻找急需的帮助
谢谢。
【问题讨论】:
-
快速修复尝试:
{postalCode: Number(searchKey)} -
@AndreiC 感谢您的回复,我尝试通过将 searchKey 作为字符串传递来搜索名称和城市时出现错误
标签: node.js mongodb api express mongoose