【问题标题】:want count of populated collection in sails js (mongodb)想要在sails js(mongodb)中填充集合的计数
【发布时间】:2016-08-10 12:52:02
【问题描述】:

我有两个模型类别和库存并关联.. 我使用的命令是:

Category.find(query).populate('inventories',{select: ['id']});

它给了我以下结果

 "categories": [
  {
    "inventories": [
      {
        "id": "4369b6bd-de15-4201-97b5-43a10e3ccb5f"
      }
    ],
    "business": "578e17a7cb25beb418ef4680",
    "name": "B",
    "createdAt": "2016-07-19T17:41:25.184Z",
    "deviceId": "353323063171945",
    "updatedAt": "2016-07-19T12:11:49.819Z",
    "id": "017af659-09ec-4f83-b5fb-b4d562912745"
  },
  {
    "inventories": [
      {
        "id": "bffa55ac-724d-454d-b02f-bb3002b6ee99"
      }
    ],
    "business": "578e17a7cb25beb418ef4680",
    "name": "A",
    "createdAt": "2016-07-19T17:40:47.009Z",
    "deviceId": "353323063171945",
    "updatedAt": "2016-07-19T12:11:49.813Z",
    "id": "efb5a472-417a-4365-89d2-a0ba46f6a9b0"
  },
  {
    "inventories": [
      {
        "id": "5c19106c-36c8-47ae-b596-97234867054e"
      },
      {
        "id": "5c191dfc-36c8-fa7ae-ber96-9df234867054e"
      }
    ],
    "business": "578e17a7cb25beb418ef4680",
    "name": "C",
    "createdAt": "2016-07-19T17:42:06.661Z",
    "deviceId": "353323063171945",
    "updatedAt": "2016-07-19T12:13:50.305Z",
    "id": "f75f59f8-6d5b-415d-9019-47c0bed5cb6a"
  },
  {
    "inventories": [
      {
        "id": "10c7c06e-cfd4-45ec-8bd7-bf77e349fc3b"
      }
    ],
    "business": "578e17a7cb25beb418ef4680",
    "name": "D",
    "createdAt": "2016-07-19T17:42:50.511Z",
    "deviceId": "353323063171945",
    "updatedAt": "2016-07-19T12:13:50.307Z",
    "id": "8ad0fee5-9efe-49dc-ae24-761860874855"
  }
]

但我想要的是填充数据只返回关联记录的计数 例如:

"inventories": [
      2
    ],
    "business": "578e17a7cb25beb418ef4680",
    "name": "C",
    "createdAt": "2016-07-19T17:42:06.661Z",
    "deviceId": "353323063171945",
    "updatedAt": "2016-07-19T12:13:50.305Z",
    "id": "f75f59f8-6d5b-415d-9019-47c0bed5cb6a"
  },

在某些网站上,我看到有一个名为 populateCount(); 的函数; 但它是说 populateCount 不是一个函数...... 请帮忙

【问题讨论】:

  • 我认为sails 没有populateCount() 功能。不过,您可以为找到的每个类别分配 category.inventories = category.inventories.length

标签: node.js mongodb npm sails.js waterline


【解决方案1】:

Sails 没有提供这样的功能,但是这个问题很容易解决。只需计算库存数组并将长度保存在新属性中。

 Category.find({ id : [1, 2] })
  .populate('inventories')
  .then(function (categories) {

    categories.forEach(function (category) {
      category.inventoriesLength = category.inventories.length;
    });

  });

【讨论】:

  • 现在如何在启用分页后对填充的项目进行排序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
  • 2017-02-07
  • 2015-11-05
  • 2017-06-10
  • 2019-08-07
相关资源
最近更新 更多