首页 > 数据库    日期:2024-03-31 / 浏览

条件查找

$regex为模糊查询的字符串提供正则表达式功能,MongoDB使用Perl兼容正则表达式

//通过条件查找,支持username模糊搜索并分页
    findAdminByParamsAndPageHasFuzzy(params, pager) {
        if (params.username) {
            let pattern = new RegExp(params.username);
            params.username = {
                $regex: pattern,
                $options: 'imxs'
            };
        }
        if (params.orgname) {
            let pattern = new RegExp(params.orgname);
            params.orgname = {
                $regex: pattern,
                $options: 'imxs'
            };
        }
        if (params.adminRoles) {
            params.adminRoles = mongoose.Types.ObjectId(params.adminRoles);
        }
        AdminHandler.searchParamsClearEmptyValue(params);
        return Promise.all([
            adminModel.find(params, { password: 0 }).count().exec(),
            adminModel.find(params, { password: 0 }).sort({
                _id: -1
            }).populate("adminRoles").skip((pager.pageIndex - 1) * pager.pageSize).limit(pager.pageSize).exec()
        ])
    }

RegExp 对象

RegExp 对象用于存储检索模式。通过 new 关键词来定义 RegExp 对象

RegExp 对象有 3 个方法:test()、exec() 以及 compile()

  • test() 方法检索字符串中的指定值。返回值是 true 或 false;
  • exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
  • compile() 方法用于改变 RegExp。compile() 既可以改变检索模式,也可以添加或删除第二个参数;
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
patt1.compile("d");
document.write(patt1.test("The best things in life are free"));

以上就是mongose 模糊检索实现示例详解的详细内容,更多关于mongose 模糊检索的资料请关注其它相关文章!

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章