How to retrieve the count of documents in a populated collection using Sails.js with MongoDB

I have two models category and inventories and they are associated. The command I used is:

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

This command returns the following result:

 "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"
  }
]

However, what I want is the populated data to only return the count of associated records. For example:

"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"
  },

I have seen in some websites that there is a function called populateCount(); but when I try to use it, it says "populateCount is not a function"... Please Help

Answer №1

Unfortunately, Sails framework does not offer a built-in function to solve this particular problem. However, resolving it can be achieved with relative ease by implementing a simple algorithm. By counting the elements within the inventories array and storing the result in a new property, the issue is resolved.

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

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

  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a time to live feature in socket.io can be accomplished by setting a

After extensive searching online, I haven't been able to find any resources on how to implement the 'time-to-live' function using Socket.io. In my project, I am utilizing Node.js with express. The functionality of the mentioned time-to-live ...

The command npm is not recognized as internal or external - utilize nvm for installation

I have been attempting to install nodejs and npm on my Windows 10 computer. Here are the steps I followed: Downloaded the nvm setup from this link Executed the nvm install wizard using nvmsetup.exe Opened command prompt and entered 'nvm install v5.1. ...

Testing asynchronous errors with Sequelize and Postgres

Recently, I've been working on writing unit tests for Sequelize with a Postgres database and using Jest for testing. While trying to get the following code to work: test('email field only takes valid emails', () => { expect.assertions( ...

Error message 'require is not defined' can occur in Meteor.js when trying to incorporate an NPM package

I'm facing an issue while trying to utilize an npm package in Meteor.js (Release 0.6.6.3) by using Meteor.require. The error thrown states that require is not defined. What could be causing this and how can it be resolved? mrt add npm npm install git ...

Asynchronous API calls nested within the Async waterfall technique

My current code utilizes async waterfall to execute two API calls, with the second call depending on data from the first one. However, I am encountering an issue where the second function begins before the first one is completed, resulting in missing data ...

What is the process for establishing a key on the request header to authenticate in Node.js?

I am a novice in the world of nodejs. My current project involves creating a basic server that writes JSON data to a CSV file. However, I have encountered a stumbling block: For authentication purposes, the request header must include an “appKey” para ...

What could be causing the error "Err: user.validPassword is not a function" to occur

I am in the process of developing a node.js app and I have implemented Passport js. After referring to the Passport-local documentation on their official website, I decided to utilize the local passport-strategy. However, I encountered an error stating tha ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

Encountering issue retrieving information from Node.js REST API in Flutter (MySQL Localhost)

ERROR: An Exception has occurred. _TypeError (type 'List' is not a subtype of type 'Map') Future<Album> fetchAlbum() async{ final response = await http.get(Uri.encodeFull("192.168.43.106:8080/customers/"), ...

What steps should I take to resolve the "Module Not Found" issue that occurs when I use the command "npm start" after setting up a new React project with npm?

Just starting out with React.js and npm and encountered an issue. After using the command: npm create react-app my-test-npm-react-app I waited for the project to be created successfully. However, when I tried running: npm start I received the followin ...

Issue encountered when trying to import 'vscode-languageserver' within a React application

I'm in the process of setting up a virtual playground using monaco-editor and vscode-languageserver to showcase the capabilities of my language server. However, when attempting to import 'vscode-languageserver' within a page like this examp ...

The server is unable to send headers to the client after they have already been sent

While performing a put request on my database, everything seems to be working fine as expected. However, there is this persistent message appearing in the console that I suspect might impede my progress. Cannot set headers after they are sent to the client ...

problem encountered during the execution of socket.io code

While browsing the Digital Ocean Community, I came across a tutorial at this link: https://www.digitalocean.com/community/tutorials/how-to-install-express-a-node-js-framework-and-set-up-socket-io-on-a-vps that discussed installing Express, a Node.js framew ...

What could be causing the issue with npm modules installation?

I've been having trouble installing the react-native-cli module, as well as any other module. Here's what I've tried: npm install -g react-native-cli When I run this command in the terminal, I keep getting an error. I've used node on ...

Setting up a secure HTTPS server in Sail.js

Greetings! I am currently working on developing a set of API endpoints for my SailJS application. As part of this process, I am looking to implement OAuth2.0 authentication with the http-bearer-token strategy. In order to achieve this, I need to ensure t ...

Ensure that the script continues to run uninterrupted even after the user has navigated away from the

Currently, I am working on an application that allows users to purchase tickets for events using technologies such as node.js, express.js, sequelize, and react. After the user completes the ticket purchasing process, they are redirected to a page indicati ...

What is causing jsdom.env to malfunction with the 'base' tag?

Latest Update: After some investigation, I discovered that the presence of the 'base' tag on a webpage can prevent jQuery from running successfully. It's strange to me why this would be the case. <base href="http://bbs.18183.com/" /> ...

Issue encountered: Vue js and d3 data visualization error - "d3 is not defined"

I am attempting to showcase a .json file as a treemap by using npm run dev. I thought I had everything set up correctly but it appears that an issue is arising. Below is my App.vue code: <template> <div id="app"> <title> { ...

Get image data from Next.JS API and show it in the web browser

I am looking to utilize my own next.js endpoints to request an image that I can then embed into my website. Currently, the issue I am facing is that the image seems to be immediately downloaded and does not display in the browser window. import type { Next ...

Combining views from two distinct collections in MongoDB

I am looking to generate a view that combines data from two distinct collections (info1, info2) in MongoDB. Specifically, I want to extract LoginId, FirstName, LastName, and Email from the info1 collection, and GroupName, Type, and MachName from the info2 ...