0

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

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"});
            }
        });
};

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

谢谢。

4

1 回答 1

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"});
        });
};

参考:$或

于 2013-11-12T11:08:26.827 回答