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 に答える