【问题标题】:Optional chaining of methods like sort, limit, skip方法的可选链接,如排序、限制、跳过
【发布时间】:2019-11-14 07:28:19
【问题描述】:

我正在传递查询参数,对于 Mongoose 查询,sortlimitskip 可以是任意组合。

我想到的是根据传递的参数创建多个猫鼬查询。因此,如果只传递了sort,那么生成的查询将有Document.find({}).sort({}),并且只传递limit,那么查询将是Document.find({}).limit({})

我应该写这样的东西吗-

router.get('/', (req, res) => {
    if(req.query.sortByPrice) {
        Property.find({})
        .sort({ price: req.query.sortByPrice === 'asc' ? 1 : -1 })
        .populate('user_id', 'name')
        .exec((err, properties) => {
            if (err)
                return res
                    .status(404)
                    .json({ error: "Can't get user details!" });
            res.status(200).json(properties);
        });
    }
    if(req.query.limit) {
        Property.find({})
        .limit(req.query.limit)
        .populate('user_id', 'name')
        .exec((err, properties) => {
            if (err)
                return res
                    .status(404)
                    .json({ error: "Can't get user details!" });
            res.status(200).json(properties);
        });
    }
});

【问题讨论】:

    标签: mongodb sorting mongoose filtering


    【解决方案1】:

    您可以从请求正文中创建变量options,并将其作为第三个参数传递给.find() 查询,无需使用if-else 块编写冗余代码。

    .find() 查询的第二个参数是projection,所以不要忘记在那里传递一个空对象。

    试试这个:

    let options={};
    if(req.params.sortByPrice){
        options.sort = {
            price: req.params.sortByPrice === 'asc' ? 1 : -1 
        }
    }
    if(req.params.limit){
        options.limit = req.parms.limit
    }
    
    Property.find({},{},options)
        .populate('user_id', 'name')
        .exec((err, properties) => {
            if (err)
                return res
                    .status(404)
                    .json({ error: "Can't get user details!" });
            res.status(200).json(properties);
            return;
        });
    

    注意:不要忘记在res.status().json()之后返回,否则你可能会得到错误cant set headers after they are sent。如果您尝试再次发送响应。

    【讨论】:

    • 解决方案有效,但我不得不将 req.params 更改为 req.query。请同时更新您的 anwser。
    • 好的,更新了,我很高兴能帮上忙。请将其标记为已接受的答案并进行投票,它将帮助其他有相同/相似问题的人,并激励我提供帮助
    猜你喜欢
    • 2019-06-30
    • 1970-01-01
    • 2015-08-20
    • 2019-05-31
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多