【问题标题】:Paginated results in mongoose with filters on reference document猫鼬中的分页结果与参考文档上的过滤器
【发布时间】:2018-03-08 08:05:19
【问题描述】:

我有一个用户并发布文件如下:

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

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

我想查询帖子并获取所有那些作者有“体育”、“跑步”作为兴趣的帖子,这将是一个分页查询。

如何在猫鼬中这样做,如果不是,我应该使用什么替代方案?

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    使用limit和skip进行分页

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

    【讨论】:

    • 我将使用 Post 模型,interests 不是 Post 模型架构上的属性,而是用户模型上的属性。
    • 您可以提出任何问题。
    • 这有什么问题?
    • 当作者被引用对象时,我怎样才能运行查询 author.interests {$in: [ "Sports", "Movies", ]}。
    • 您要对作者或帖子进行分页吗?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2016-11-02
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 2020-10-08
      • 1970-01-01
      相关资源
      最近更新 更多