想要在帆js(mongodb)中填充人口集合的数量

时间:2016-08-10 12:52:02

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

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

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不是一个函数...... 请帮忙

1 个答案:

答案 0 :(得分:3)

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

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

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

  });