【问题标题】:How to Check current user's vote before votes are grouped and sumed in same aggregate function如何在投票被分组并在同一聚合函数中求和之前检查当前用户的投票
【发布时间】:2016-10-19 01:31:45
【问题描述】:
var PostSchema = new mongoose.Schema({
    item: {
    type: mongoose.Schema.ObjectId,
        ref: 'item',
        required: true
    },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
  vote: {
    type: Number,
    default: 0
  },
  total: {
    type: Number,
    default: 0
  },
  awsPostKey: {type: String},
  picture: {type: String, required: true}
});

var data = function(){
return Post
.find({})
.then(function(post){
    return post;
 })
};


var userId = //mongo objectId for current user

//postVote schema:
var PostVoteSchema = new mongoose.Schema({
  post: {
    type: mongoose.Schema.ObjectId,
        ref: 'Post',
        required: true
    },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
  vote: {
    type: Number,
    default: 0
  }
});

//pass data from Post query to PostVote sum function:

PostVoteSchema.statics.sum = function (data, userId) {

 var postIds = data.map(function (a) {
    return a._id;
  });

return PostVote
.aggregate(
    [
   { $match: { 'post': {$in: postIds}}},
   { $group: { _id:'$post' ,vote:{$sum:'$vote'}}}
 ])
.execAsync()
.then(function(votes){

    return votes;

   //desired output to client, _id is for specific post
   {_id: 5802ea4bc00cb0beca1972cc, vote: 3, currentUserVote: -1}

 });
};

我成功地获得了具有相同 postId 的所有选票的总和。 现在,我想查看当前用户 (userId) 是否也对给定的帖子进行了投票,然后返回他们的投票方式(+1 或 -1)以及对特定帖子的所有投票的总和.

是否可以这样做,或者我必须在我的聚合管道之外执行此操作 - 在第二个查询中?不得不再次查询该集合似乎很费力。

【问题讨论】:

  • 您能否也显示一些给定示例文档的预期输出?
  • 确定,我会添加预期的 JSON

标签: mongodb aggregation-framework mongodb-aggregation


【解决方案1】:

是的,这是可能的。在 $group 管道中,您可以使用 $cond 运算符作为输入 $sum 累加器运算符的逻辑。例如:

return PostVote.aggregate([
   { "$match": { "post": { "$in": postIds } } },
   { 
        "$group": {
            "_id": "$post",
            "votes": { "$sum": "$vote" },                 
            "userVotes": {
                "$sum": {
                    "$cond": [
                        { "$eq": ["$user", userId] },
                        "$vote",
                        0
                    ]
                }
            }
        }
    }
 ]).execAsync().then(function(votes){
    return votes;
});

【讨论】:

  • 这个“仅”是否会为用户返回总和?
  • 是的,因为userVotes 字段仅对userId 的投票进行有条件地求和。
  • 是否有返回所有与 postId 匹配的投票,然后以某种方式标记同一管道中存在 userId 的帖子?也许与第二组..
  • 您能否为此创建一个新问题,可能显示一些示例文档和聚合查询的预期输出?
  • 好的,这在技术上是我最初的问题。添加更多细节或添加新细节会更好吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2010-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多