【问题标题】:Mongoose: How can I concatenate the result of two sorted queries?Mongoose:如何连接两个排序查询的结果?
【发布时间】:2013-11-12 19:18:49
【问题描述】:

在我的应用中,我有一个用户提交的故事列表。用户可以将故事标记为私有,这样只有他们才能看到这些故事。我需要检索进行查询的用户的所有公共故事和私人故事的列表,并且需要对其进行排序,以便我可以使用分页。到目前为止,我有这样的东西。

story.index = function(req, res, next) {
    return Story.find({isPrivate: false})
        .sort('-date_modified')
        .exec(function(err, stories){
            if(err){
                return next(err);
            }

            /* If the user is authenticated, get his private stories */
            if(req.isAuthenticated()){
                Story.find({ _creator: req.user._id })
                .sort('-date_modified')
                .exec(function(err, privateStories){
                    /* Create a list with all stories */
                    var all = stories.concat(privateStories);

                    /* If have something in the list, return it */
                    if(all.length > 0){
                        return res.send(all);
                    }
                    /* Return a 404 otherwise */
                    else{
                        return res.send(404, {message: "No stories found"});
                    }
                });
            }

            /* If the user is not authenticated, return the public stories */
            else if(stories.length > 0){
                return res.send(stories);
            }
            /* Or a 404 */
            else{
                return res.send(404, {message: "No stories found"});
            }
        });
};

但这显然不是按顺序添加私人故事。我怎样才能得到这个结果?

谢谢。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    如果我没听错,为什么不在第一个查询中添加私有过滤,而不是进行 2 个查询?

    story.index = function (req, res, next) {
        var filters
    
        /* If the user is authenticated, get his private stories */
        if (req.isAuthenticated()) {
            filters = { $or: [
                {isPrivate: true, _creator: req.user._id},
                {isPrivate: false}
            ]}
        } else {
            filters = {isPrivate: false}
        }
    
    
        return Story.find(filters)
            .sort('-date_modified')
            .exec(function (err, stories) {
                if (err) {
                    return next(err);
                }
    
                /* If the user is not authenticated, return the public stories */
                if (stories.length > 0) {
                    return res.send(stories);
                }
    
                /* Or a 404 */
                return res.send(404, {message: "No stories found"});
            });
    };
    

    参考:$or

    【讨论】:

    • 谢谢!我正在寻找它,我找不到任何关于过滤器的信息,而“$or”过滤器正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2013-06-24
    相关资源
    最近更新 更多