通过环回获取所有用户不建议使用相同帖子的用户

时间:2017-07-06 04:27:27

标签: mongoose loopback

假设我有以下集合: 1- users 2- posts 3- postSuggestion

postSuggestion我有userId, postId, suggesterId,我现在想要做的就是不建议所有发布标识为12345的用户。 我到目前为止尝试的是:

 getAllUsers(): Observable<any> {
   var currentUserId = this._postUserApi.getCurrentId();
   return this._http
     .get(`api/postsUsers?filter[where][id][neq]=`+currentUserId+`&filter[fields][id]=true&filter[fields][firstName]=true&filter[fields][lastName]=true`)
     .map((res: Response) => res.json())
     .catch(this.handleError);
 }

上面的函数返回除登录用户以外的所有用户,但是想要再添加一个条件来检查那些以前没有建议过相同帖子的用户。

3 个答案:

答案 0 :(得分:1)

从api url看,您的电流如下所示

filter:{
    where:{
      id:{
        neq: $currentUserId // your user id
      }
    },
    fields:{
      is: true,
      firstName: true,
      lastName: true,
    }
}

您需要的是额外的过滤器。您可以像以下

那样实现此目的
filter:{
    where:{
      and:[
        id:{ neq: $currentUserId },
        post_id: 12345
      ]
    },
    fields:{
      is: true,
      firstName: true,
      lastName: true,
    }
}

答案 1 :(得分:1)

不幸的是我从未使用过mongoose,但是如果你有权访问数据库,你可以尝试这个查询:

db.postSuggestion.aggregate([
    {$match: {
        suggesterId: {$ne: 2}, // suggesterId=2
        postId: {$ne: 1} // postId=1
    }},
    // remove dups userId will become _id
    {$group: {
        _id: "$userId"
    }},
    // recover user data
    {$lookup: {
        from: 'user',
        localField: '_id',
        foreignField: 'userId',
        as: 'user'
    }},
    // unwind user array
    {$unwind: '$user'},
    // project user name and id only
    {$project: {
        _id: 0,
        'user.userId': 1,
        'user.name': 1
    }}
])

顺便说一句,我不建议将MongoDB用作关系数据库,但是如果你想继续使用它,那么我强烈建议你改变你的数据模型,保留一个集合并更新文档,你的疑问会变得不那么混乱。

Bonus:Robomongo是一个免费的MongoDB GUI,它对测试你的查询非常有用。

答案 2 :(得分:0)

如果你想要一些解决方案,你必须提供你正在使用的东西,所以我们可以有一个共同点来讨论。如果你想要一个概念性的想法,

答案应该是

not yet receive suggestion users = <all users> - <select userId from postSuggestion where postSuggestion.postId = 12345> - currentUserId