最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

在Node.js中动态构建Mongoose聚合查询

IT培训 admin 12浏览 0评论

在Node.js中动态构建Mongoose聚合查询

我正在尝试根据POST api调用中传递的数组变量的内容动态构建猫鼬聚合查询,如下所示,但是我总是收到错误“ $ or / $ and / $ nor条目,是完整的对象”所以想知道是否有人可以在下面查看我的代码,请让我知道我可能丢失了什么/做错了吗?

static search (searchData) {
    let { searchTerm, filterBy } = searchData;
    searchTerm = Utils.escapeRegexSpecialCharacters(searchTerm);

    let filterByElementsLength = filterBy.length; 
    if(filterByElementsLength === 0) {
        query.push({
            $match: { 'bookTitle': new RegExp(searchTerm, 'i') },
        });
    }else if (filterByElementsLength > 0) {            
        query.push({
            $match: { $and: [ 
                { 'bookTitle': new RegExp(searchTerm, 'i') },
                filterBy 
            ] }                
        });
    }
}

考虑到使用Postman通过以下内容示例将filterBy内容发布为JSON(Application / json):

"filterBy": [{"author": "Michael White" }, { "Price_Less_Than": "100" }],

感谢您的支持

回答如下:

[找到一个解决方案,将其发布在下面:

在Node.js中动态构建Mongoose聚合查询

我正在尝试根据POST api调用中传递的数组变量的内容动态构建猫鼬聚合查询,如下所示,但是我总是收到错误“ $ or / $ and / $ nor条目,是完整的对象”所以想知道是否有人可以在下面查看我的代码,请让我知道我可能丢失了什么/做错了吗?

static search (searchData) {
    let { searchTerm, filterBy } = searchData;
    searchTerm = Utils.escapeRegexSpecialCharacters(searchTerm);

    let filterByElementsLength = filterBy.length; 
    if(filterByElementsLength === 0) {
        query.push({
            $match: { 'bookTitle': new RegExp(searchTerm, 'i') },
        });
    }else if (filterByElementsLength > 0) {            
        query.push({
            $match: { $and: [ 
                { 'bookTitle': new RegExp(searchTerm, 'i') },
                filterBy 
            ] }                
        });
    }
}

考虑到使用Postman通过以下内容示例将filterBy内容发布为JSON(Application / json):

"filterBy": [{"author": "Michael White" }, { "Price_Less_Than": "100" }],

感谢您的支持

回答如下:

[找到一个解决方案,将其发布在下面:

发布评论

评论列表 (0)

  1. 暂无评论