猫鼬填充选项限制,如何限制子文件数量? [英] Mongoose populate options limit, how to limit number of sub document?

查看:61
本文介绍了猫鼬填充选项限制,如何限制子文件数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询来查找帐户并填充该帐户的子文档.

I have a query to find an account and populate sub doc of the account.

当我使用填充路径:订单"时,限制选项将起作用.但是,如果我使用填充路径"orders.order",则选项限制将不起作用.

When I use populate path:"orders" the limit option will work. But if I use populate path"orders.order", the option limit will not work.

我该怎么办?

我的模式如下:

  var AccountSchema = new mongoose.Schema({

    _id:id,
    orders:{type:[{
      order:{type: mongoose.Schema.Types.ObjectId, ref:'Order'}
    }]}
  });


var findOrderByUserId = function(accountId,index,count,callback){
  var limit = index*count;
  console.log(limit);
  Account.findOne({_id:accountId}).populate({
    path:'orders.order',//If path is orders, then limit will work

    options:{
      limit:limit
    }
  }).exec(function (err, doc) {
              if (err) {
                console.log(err);
                callback(err);
              }
              console.log(doc);
                var array = [];
                for(var i=limit - count;i<doc.orders.length;i++){
                    if(doc.orders[i]!=null){
                        array.push(doc.orders[i]);            
                    }
                    else{
                      break;
                    }
                }
              callback(doc);
          })
}

推荐答案

limit仅适用于顶级文档,以控制需要使用$slice的文档中的数组,因此,您需要重建查询,就像这样(mongo shell):

limit works only with top level documents, to control arrays inside a document you need to use $slice, so that means you need to rebuild your query, like this (mongo shell):

db.posts.find( {}, { comments: { $slice: 5 } } )

有关更多信息-和示例,请参见这篇文章.

see this post for more info - and example:

query.slice('comments', 5)
// or...
query.where('comments').slice(5)

手册

这篇关于猫鼬填充选项限制,如何限制子文件数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆