SailsJs Paginate连接对象列表

时间:2016-07-05 11:03:43

标签: javascript node.js pagination sails.js waterline

我有一个可能与另一个模型相关或不相关的模型。这是我的模型结构:

// Post.js
attributes: {
    sender: { model : 'user' },
}

// User.js
attributes: {
    posts: { collection: 'post', via: 'sender', dominant: true }
}

所以帖子模型我或可能不会附加到发件人。发件人可以是用户也可以是null。

我需要能够获取特定于特定用户的所有帖子以及所有没有发件人的帖子。一旦我拥有这两个,我需要连接它们。以下是我必须执行此操作的代码:

// Before this I use a native query to get a list of posts with no sender. This is "searchIds".
filterData.id = searchIds;
filterData.subject = 1;
posts = [];

        // Populate questions that were sent to all users
        Post.find()
            .where(filterData)
            .exec(function (err, response) {
                if(err) return res.serverError(err);
                // We add all of the posts with no senders to the messages array
                if (response.length > 0){
                    posts = posts.concat(response);
                }

                delete filterData.id;

                // Now we get the posts specific to this user.
                User.findOne({id:id})
                .populate('posts',{ where: filterData })
                .exec(function(err, results){
                  if(err) return res.serverError(err);
                    if (results && results.posts && results.posts.length > 0){
                        posts = posts.concat(results.posts);
                    }
                    return res.json(posts);
                });
        });

这可以查找并获取由该特定用户和所有没有发件人的帖子发布的一系列帖子,但我现在需要做的是对此列表进行分页。我通常这样做的方法是使用Sails / Waterline paginate方法,但因为我将两个单独的DB调用连接在一起,我不知道我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以将两个查询与水线or功能结合起来。

Post.find({
    or: {
        {sender: null}, // finds 'no sender' posts
        {sender: senderId} // finds posts where sender's id is senderId 
    }
})
.paginate({ page: 2, limit: 10 })
.then(function(posts) {
    return res.json(posts);
})
.catch(function(err) {
    return res.serverError(err);
})

我很确定你甚至可以编写像

这样的查询查询
Post.find({sender: [null, senderId]})

并获得相同的结果。

相关问题