Paginated导致mongoose与参考文档上的过滤器

时间:2018-03-08 08:05:20

标签: node.js mongodb mongoose mongodb-query

我有一个用户和帖子文件如下:

user: {
"name": "Test",
interests: [
  "Sports",
  "Movies",
  "Running"
 ]
}

post: {
 "title": "testing",
 "author": ObjectId(32432141234321411) // random hash   
}

我想查询帖子并获取所有这些帖子,作者有" sports"," Running"作为兴趣,这将是一个分页查询。

我怎么能在猫鼬中这样做,如果没有,我可以用什么方法?

2 个答案:

答案 0 :(得分:1)

使用限制分页并跳过

var limit = 5;
var page = 0; // 1,2,3,4

return Model.find({
        /* Some query */
    })
    .limit(limit)
    .skip(limit * page)
    .exec().then((data) => {
        console.log(data);
    });

试试这个

const findUser = (interests) => {
    return User.find({
        interests: {
            $in: interests
        }
    }).exec();
};

const findPost = (query, page = 0) => {
    const limit = 5;
    return Model.find(query)
        .limit(limit)
        .skip(limit * page)
        .exec();
};

var execute = async () => {
    const users = await findUser(["Sports", "Movies", ]);
    users.forEach(user => {
        user.post = await findPost({
            "post.author": user._id
        });
    });
    return users;
}

答案 1 :(得分:0)

我使用了以下方法虽然给出了async / await方法的答案,但实际上我使用了promises。

const fetchPosts = async (req, res) => {
  //First find users having those interests.
 const users = await User.find({ 
    interests: {
     "$in": ["Sports", "Movies"]
    } 
  })
  .select('_id')
  .exec();

 // map over array of objects to get array of ids
 const userIds = users.map(u => u._id);

 // Then run an in filter on Post collection against author and 
 //userIds
 const posts = await Post.find({
   author: {
     "$in": [userIds]        
    } 
  }) 
  .limit(15)
  .skip(0)
  .exec();
}