Mongoose Query: Calculate the number of elements in an array

My Schema contains an array of ObjectIds:

const userSchema = new Schema({
    ...
    article: [{
        type: mongoose.Schema.Types.ObjectId,
    }],
    ...
},

https://i.sstatic.net/RcXTF.png

In the example above, I want to count the elements in the array, which should be 10.

I attempted the following method, but it didn't work for me. The req.query.id represents the _id of the user and is used to filter the specific user with a matching article array.

const userData = User.aggregate(
    [
        {
            $match: {_id: id}
        },
        {
            $project: {article: {$size: '$article'}}
        },
    ]
)
console.log(res.json(userData));

The console.log(article.length) currently returns 0. How can I achieve this? Is using the aggregate function the correct approach, or is there a better way to count elements in an array?

Answer №1

Consider the benefits of utilizing aggregate even when an array of ids is already associated with the user object.

To incorporate articles as a reference field:

const {Schema} = mongoose.Schema;
const {Types} = Schema;

const userSchema = new Schema({
    ...
    article: {
      type: [Types.ObjectId],
      ref: 'Article',
      index: true,
    },
    ...
});

// include a virtual property if desired
userSchema.virtual('articleCount').get(function () {
  return this.article.length;
});

Retrieve articles using populate method:

const user = await User.findById(req.query.id).populate('articles');

console.log(user.article.length);

Alternatively, handle arrays of ids without populating:

const user = await User.findById(req.query.id);

console.log(user.article.length);

Utilize the virtual field for easy access:

const user = await User.findById(req.query.id);

console.log(user.articleCount);

It's worth considering using aggregate for complex post-filter logic that essentially involves aggregation. For instance, when you need to process a result set on the database side to obtain specific information efficiently, such as extracting users based on articles added on a particular day and grouping them by hour.

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

NodeJS Try-Catch not causing blockage

Why is the for-loop still executed and causing a TypeError even after catching the failure of JSON.parse() and terminating the client request with res.end()? It's almost as if the try-catch block is asynchronous, leading to this confusing outcome. co ...

Ensuring an equal count of vowels and consonants through Regex validation

Could someone please provide guidance on how I can perform Regex form validation in JavaScript? The student's name must consist of only alphabet characters, with an equal number of vowels and consonants. ...

What steps can I take to resolve the issue of item display in the dropdown menu?

My objective is to have a dropdown list with "title 1234" appearing first. When this option is selected, its value should be 1234. How can I achieve this? Here is the desired outcome: https://i.sstatic.net/CqWgn.png Currently, the list looks l ...

Executing an AJAX request in the onsubmit event of a form results in the form submission proceeding even when return false is

I am facing an issue with a form that I intend to use only for an AJAX call. The AJAX call is triggered on submit in order to utilize the auto-check feature for required fields. Despite returning false on submit, the form still submits. Surprisingly, when ...

Obtain JSON information using an underscore template

As someone fairly new to using Backbone and Underscore, and web development in general, I am seeking guidance on how to retrieve individual model data on-click from a template format in order to populate a pop-up modal. Any advice or direction would be gre ...

What is the method to identify the test case name as passed or failed in Puppeteer?

I am currently working on integrating the puppeteer-jest test framework with TestRail using TestRail API. To accomplish this task, I need to identify which tests have failed and which tests have passed. Despite searching through the official GitHub Reposi ...

Automated clicking on JavaScript notifications

I am currently testing my web application, where I display a JavaScript Notification using new Notification("Title"). In order to verify specific behavior triggered by clicking on the notification, how can I simulate a user click event in JavaScript? ...

Is there just a single model in operation?

I'm facing a strange issue where only one of my models is working correctly. The "toDo" model updates just fine, but the "clicked" and "addToDo" models are not updating or responding to clicks: utilizing MVC <head> <title>ToDo</title& ...

Extracting information from a Go template within an AngularJS environment

I am brand new to Angular Js. I successfully retrieved data from golang in angular js. However, when I use it in an alert box, it displays as [object Object]. I attempted to fix this issue by changing the delimiters of golang from {{ }} to <<< > ...

How can you access a Mongo collection within its own Schema method?

My goal with this approach is to automatically create a unique username for users upon registration. I also want to ensure that the generated username is not already in use. The challenge lies in querying the 'User Collection' within the method ...

When a webpage reload triggers a 404 error, my website's iframe with the source "videoUrl | sanitize" will display

I am attempting to retrieve a videoUrl from a database and set it to the iframe [attr.src] in order to display a YouTube video. It is imperative that the data originates from the database, as there are limitations preventing us from directly uploading and ...

Efficiently assigning unique keys to set values for multiple objects in React JS

Can someone assist me in updating the values in multiple objects? Here is a sample object structure: constructor(props){ this.state = { objData : [{ score:{q1:null,q2:null,q3:null}, data:{id:123, name:"Steven CHS"} }, { ...

Verify the uploaded file: Confirm that it is a valid image

Is there a way to determine in JavaScript if the uploaded file is a valid image? <input type="file" name="uploadPicture"/> I am aware that I can check the file extension, but this method is not foolproof since someone could simply change a .txt fil ...

Scrolling down within a Bootstrap modal

I'm working on a bootstrap modal and looking to implement a scroll down feature upon button click: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <!-- Modal --> ...

JavaScript is not behaving as expected when utilizing a For loop, as the values of objects are

Working with MongoDB in a Node.js environment, I have a call that retrieves a list of users with various fields including name, email, role, and _id. However, I want to modify this field before sending the data to the frontend of my application. To achieve ...

405 error: NGINX blocking POST method in Django DRF Vue.js application

I have encountered a strange issue while building my ecommerce site. Everything seems to be working fine, except for the forms. When attempting to post content, I keep receiving a 405 method get not allowed error. It's confusing as I am trying to use ...

Ajax insertion was successful, but the database records are empty

Why is my code able to save data to the database using Ajax, but all rows are empty? Here is My Form: <form name="frm" id="frm" action=""> <div class="form-group"> <label for="namaproduk">Product Name</label> <input t ...

The Heroku PHP framework does not support the use of MongoCollection::aggregate() when using MongoHQ as

Encountering an issue while using MongoDB's aggregate() function in PHP code. The code functions correctly on my local environment running MongoDB version 2.2.3. PHP Fatal error: Call to undefined method MongoCollection::aggregate() in /app/www/page. ...

Angularjs pledged to utilize $http for its functionality

$http({ url: '/verifyUserName', data:{username:$scope.username}, method: "POST" }) .then(function(response) { $scope.allowGameStart = true; }) Is there a way to access the variable $scope.allowGameStart outside of the promise in ...

Issue with regex compatibility in Internet Explorer 7 - Regex pattern functioning correctly across all browsers except IE7

My password validation regex ensures that the password is between 6 and 25 characters long, and contains at least one number. var passwordRegEx = /^(?=.*\d)(?=.*[a-zA-Z]).{6,25}$/; if(!#quickRegister_Password').val().test(pass)) { errorMgs += ...