【问题标题】:Populate limited number of items in array, but keep array length - mongoose在数组中填充有限数量的项目,但保持数组长度 - mongoose
【发布时间】:2017-03-29 03:06:43
【问题描述】:

使用架构

var CommentSchema = new Schema({
  text: { type: String },
  replies: [{ type: mongoose.Schema.ObjectId, ref: 'Comment' }]
});

我有一个类似的查询

Comment.findById(req.params.id)
  .populate({
    path: 'replies',
    model: 'Comment',
    options: {
      limit: 2
    }
  })
  .exec(...)

现在我看不到在数组中填充有限数量元素并保持数组长度的选项。

我考虑填充到不同的“目标”字段,以便原始回复数组保持不变(因此有关回复数量的信息)。但我认为这个选项在 mongoose populate() 中不存在。

用例可以在 Youtube cmets 上看到。评论包含回复的数量,但只显示有限的回复数量。

【问题讨论】:

    标签: mongodb mongoose mongoose-populate


    【解决方案1】:

    我使用以下技巧来处理这种情况。

    var idToSearch = mongoose.Types.ObjectId(req.params.id)
    
    var aggregation = [
        {$match : {_id : idToSearch}},
        {$project : {
          _id : 1,
          replies: {$slice : ['$replies',5]},
          totalreplies : {$size : "$replies"},
        }}
      ];
    models.Comment.aggregate(aggregation)
        .exec(function(err, comments) {
          if(err){
            // return error 
          }
          else if(!comments){
            // return data not found
          }else {
            models.Comment.populate(comments,
              { path: 'replies'},
              function(err, populatedComments){
                if(err){
                  // return error
                }
                else {
                  console.log('comments ',populatedComments);
                }
              });
          }
        });
    

    希望对你有帮助

    【讨论】:

    猜你喜欢
    • 2019-07-28
    • 2019-03-28
    • 2014-12-05
    • 2019-01-31
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多