[英]querying mongodb collection for regex using mongoose
I am trying to query using regex
for mongoose
, I have seen other posts which have similiar suggestions but I still couldn't figure out, and also getting new errors instead of just getting a null document
back. 我正在尝试使用
regex
查询mongoose
,我看过其他帖子,它们具有类似的建议,但我仍然无法弄清楚,而且还会收到新的错误,而不仅仅是获得null document
。
I am trying to query
value contains
instead of the need of the exact to get results
我正在尝试
query
值contains
而不是确切获取results
for my route, I have something like this 对于我的路线,我有这样的东西
router.get('/:name/:value', (req, res, next) => {
const o = {};
const r = `.*${req.params.value}.*`;
// the above gives me error such as CastError: Cast to string failed for value "{ '$regex': '.*y.*' }" at path "username" for model "Model"
o[req.params.name] = { $regex: { $regex: r }, $options: 'i' };
Model.find(o, (err, doc) => {
if (err) return next(err);
res.send('success');
});
});
can someone give me a hand where I have been doing wrong? 有人可以帮我解决我做错的地方吗?
Thanks in advance for any help. 在此先感谢您的帮助。
Suppose below is your Model 假设下面是您的模型
//Employee.js
import mongoose from 'mongoose';
const Employee = mongoose.Schema({
Name: { type: String, default: "" },
Age: { type: Number, default: 0 },
Email: { type: String, default: "" },
}, { collection: 'Employee' });
export default mongoose.model('Employee', Employee);
Your router must be like below 您的路由器必须如下所示
var Employee = require('../path/to/Employee.js');
router.get('/name/:value', (req, res, next) => {
let query = {
Name: {
$regex: req.params.value,
$options: "i"
}
};
Employee.find(query, (err, docs) => {
if (err) return next(err);
console.log("Documents-->", docs)
res.send('success');
});
});
You no need to give separate param for name just do query like above 您无需像上面那样查询就为名称提供单独的参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.