分页对象的连接列表

SailsJs Paginate concatenated list of objects

本文关键字:列表 连接 对象 分页      更新时间:2023-09-26

我有一个模型,它可能与另一个模型相关,也可能不相关。下面是我的模型结构:

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

所以帖子模型可以不附加到发送者。发送方可以是用户,也可以是空值。

我需要能够获得特定于特定用户的所有帖子以及没有发送者的所有帖子。一旦我有了这两个,我需要把它们连接起来。下面是我要做的代码:

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

这工作找到并得到我的帖子的数组,由特定的用户和所有的帖子,没有一个发件人,但我现在需要做的是分页这个列表。我通常会这样做的方式是使用风帆/水线分页方法,但因为我连接两个单独的DB调用在一起,我不知道我怎么能做到这一点?

您可以将这两个查询与Waterlines 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]})
并得到相同的结果