【问题标题】:Create a complexe parse server or mongodb query创建复杂的解析服务器或 mongodb 查询
【发布时间】:2017-03-24 05:00:13
【问题描述】:

我正在使用 parse server + mongodb 作为后端,我需要帮助来创建复杂的查询:

首先这是我的数据库的架构:

friends 模型代表两个用户之间的友谊。 每个user 都有一个city

我想要实现的是创建以userId 作为输入并返回城市列表的函数按朋友数量排序

这是我到目前为止的代码

function getCities(userId) {

  //This query allow to count number of friends in a given city 
  var innerQuery1 = new Parse.Query(Friends);
  innerQuery1. equalTo("user1", userId);

  var innerQuery2 = new Parse.Query(Friends);
  innerQuery2.equalTo("user2", userId);

  countFriendsQueryInCity = Parse.Query.or(innerQuery1, innerQuery2);
  countFriendsQueryInCity.equalTo("city", cityId)
  countFriendsQueryInCity.count({..})

  //This to get all cities
  var query = new Parse.Query(City);
  query.find({})

}

所以问题是我无法在 parse 或 mongodb 中找到加入这两个查询的方法?

【问题讨论】:

    标签: javascript mongodb parse-platform parse-server


    【解决方案1】:

    Parse 目前不支持聚合查询。这是一个如何使用 js sdk api 执行此操作的示例。如果你很好奇,为了确保这有效,在我签出的 parse-server repo 版本中,我在 spec 目录中创建了一个 spec 文件,其中包含以下所有内容,然后我只专注于测试(在“describe”前面加一个“f”)。

    /**
     * Return a sorted list of cities with count of friends in that city
     *
     * @param userId id of the user to build the list for
     * @returns an array of city, count pairs sorted descending
     */
    const getCities = function getCities(userId) {
      const aggregation = {};
      const userPointer = new Parse.Object('Person').set('objectId', userId);
      return new Parse.Query('Friend')
        .equalTo('user1', userPointer)
        .include('user2.city')
        .each((friendship) => {
          const city = friendship.get('user2').get('city').get('name');
          if (aggregation[city]) {
            aggregation[city]++
          }
          else {
            aggregation[city] = 1;
          }
        })
        .then(() => {
          const sortable = [];
          for (const city in aggregation) {
            sortable.push([city, aggregation[city]]);
          }
          return sortable.sort((a, b) => b[1] - a[1]); // desc
        });
    }
    
    
    // the unit test for the function above....
    fdescribe('play with aggregations', () => {
      it('should count friends by city and order desc', (done) => {
    
        // create cities
        const ny = new Parse.Object('City').set('name', 'ny');
        const sf = new Parse.Object('City').set('name', 'sf');
    
        // create some people to befriend
        const people = [
          new Parse.Object('Person').set('city', ny),
          new Parse.Object('Person').set('city', sf),
          new Parse.Object('Person').set('city', sf),
          new Parse.Object('Person').set('city', sf),
        ];
    
        // the object of these friendships
        const friendee = new Parse.Object('Person').set('city', sf);
    
        // make the friendships
        const friends = people.map(person =>
          new Parse.Object('Friend')
            .set('user1', friendee)
            .set('user2', person));
    
        // just saving the friends will save the friendee and cities too!
        Parse.Object.saveAll(friends)
          // all saved, now call our function
          .then(() => getCities(friendee.id))
          .then((result) => {
            const lastResult = result.pop();
            const firstResult = result.pop();
            expect(lastResult[0]).toBe('ny');
            expect(lastResult[1]).toBe(1);
            expect(firstResult[0]).toBe('sf');
            expect(firstResult[1]).toBe(3);
            done();
          })
          .catch(done.fail);
      });
    });
    

    【讨论】:

    • 谢谢!所以你得到所有用户朋友的列表,然后循环朋友列表并计算城市,它?另外,如果用户有成千上万的朋友,那会太复杂,因为 parse 不能处理每页超过 1000 个项目?
    • Parse.Query.each() 没有限制。它会贯穿所有这些。问题是如果有数十万或数百万,它可能会使连接超时。另一种方法是在“Friend”类上创建一个“beforeSave”钩子,并将聚合存储在保存位置,而不是在需要时查找它。所以你可以有一个像 FriendCityCount 类的东西,它有用户 ID、城市、计数作为列.....
    • 我想过,但是这添加了另一个表来处理,其他功能......这就是为什么 NoSql 不支持连接查询
    • Mongo dpes 支持聚合。它们只是还没有被解析暴露。不过,其中一位解析服务器贡献者热衷于添加它们。
    • 该解决方案有效,但它只显示我有朋友的城市,没有列出我没有朋友的城市)。
    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多