How to search for an object within an array using MongoDB and Express.js

In my "equipos" database, the structure is as follows:

    [   
    "_id" : ObjectId("5ae4ea9f434d9b51dad68813"),
    "team_name" : "Alavés",
    "nombre_equipo_movil" : "ALA",
    "cantidad_integrantes" : 20,
    "partidos_jugados" : 29,
    "partidos_ganados" : 10,
    "partidos_empatados" : 1,
    "partidos_perdidos" : 18,
    "goles_a_favor" : 26,
    "goles_en_contra" : 45,
    "players" : [
            {
                    "dorsal" : 1,
                    "nombre_jugador" : "Fernando Pacheco",
                    "edad" : 25,
                    "nacionalidad" : "España",
                    "posicion" : "Portero",
                    "goles" : 0,
                    "asistencias" : 0,
                    "amarillas" : 4,
                    "rojas" : 1
            }
            ...
            ]
    ... 
    ]

I am trying to find out if there is a player with "dorsal" equal to 1 in the team Alavés. I have written the query as follows:

db.equipos.findOne({"team_name": "Alavés" }, {"players": {$elemMatch: {"dorsal": 1l}}})

However, the issue arises when there is no player found with dorsal 1, and the response displays the team's ID like this:

{ "_id" : ObjectId("5ae4ea9f434d9b51dad68813") }

This poses a problem for me when I try to compare the response against null using Express:

    dbo.collection("equipos").findOne(
        {"team_name": sReq.body.nombre_equipo }, {"players": {$elemMatch: {"dorsal": sReq.body.dorsal}}},
        function(err, res){

Do you have any suggestions on how I can determine if the searched player does not exist based on this type of response?

Answer №1

Experiment using .....dorsal:parseInt(sReq.body.dorsal).... – The reason being req.body.xxx is identified as a string, while dorsal is of type Number. Therefore, it is necessary to convert the string into a number using the parseInt method.

Answer №2

Instead of checking if res is equal to null, consider comparing the length of its keys by using Object.keys(res).length == 1. I'm not sure why your query is producing that particular result, but this approach might provide some clarity.

if(Object.keys(res).length == 1) {
    console.log("No player found!");
} else {
    console.log("Hey there!");
}

Answer №3

When using the Mongoose findOne method, you have the option to include a second argument specifying which fields to select.

For example, your query should look like this:

dbo.collection("equipos").findOne(
        {"team_name": sReq.body.team_name,
         "players": {$elemMatch: {"number": sReq.body.number}}
        }, function(err, res){

It's important to note that the fields you want to query should be included as the first argument, and the callback function should be passed as the second argument when not specifying the fields to select.

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

Is there a way to ensure that a method is always called in JavaScript after JQuery has finished loading

We recently integrated jquery load into our website to dynamically load content into a div without refreshing the whole page. However, we've noticed that in the complete function, we have to constantly re-apply various bindings. Is there a way to set ...

AWS Lambda serverless deployment of Angular Universal is failing to detect javascript files in the dist/browser directory

After following the steps in this tutorial for deploying to a lambda function, I encountered some issues. When testing it using serverless offline, I kept getting 404 errors for each compiled JS file. However, once I deployed it, the errors changed to 403. ...

The implementation of a function in NodeJS to interact with MongoDB seems to be malfunctioning

Can anyone help me with implementing a put function in NodeJS to manipulate a MongoDB collection? I've noticed that many people use app.get or app.post with db.collection.updateOne(), but I'm not convinced that this is the best approach. Unfort ...

Attempting to automatically change the selected input radio button every 3 seconds using HTML

Hey there, I'm just starting out with coding and StackOverflow. I'm attempting to create a basic slider but for some reason, the images are not changing. My goal is to cycle through checked input radio buttons every 3 seconds, but something seems ...

Incorporate HTML and JavaScript to dynamically show a button when a specified condition evaluates as true and hide the button if the

I need help with a scenario where I want to show a button only when a specific variable reaches a certain value. For instance, if the variable equals 5, the button should be displayed; otherwise, it should be hidden. Here are the two buttons included withi ...

The attempt to compress the code from this particular file within the node_modules directory was unsuccessful

Hey there! I'm facing an issue while attempting to compile my React project using npm run build. Upon running this command in the console, I encountered the following error message: Failed to minify the code from this file: ./node_modules/react- ...

Learn how to implement the JQuery ReplaceWith function with the resources provided by materials.io icon

I would like the favorite_border icon to switch to the favorite icon when clicked. As we are using material.io and both icons have the class material-icons, I am unsure about how to implement this using jQuery. What steps should I take to achieve this? (w ...

Retrieving the maximum date in MongoDB using C# through the Aggregate method

The following sample shows the structure of the documents: { ContractNumer: 10, SomeField: "ABC", ValueContract: 17.7, DataProcessing: '2021-01-19 10:23:20:10', Status: 1 } When working with the C# mongodb driver, how can you ...

Understanding the functionality of app.locals within app.get in an Express application and how to effectively parse data

I am currently developing a parse application using express. In my index file, I want to display different information to users based on whether they are logged in or not. However, I am facing an issue with storing the flag and logged-in user name using ap ...

How to toggle the visibility of a search bar in ReactJS?

I am trying to implement a simple search bar in reactjs without a dedicated close button. I want the same button to toggle between opening and closing the search bar. Below is the code snippet I have experimented with, but unfortunately, it's not fun ...

Customizing the default image of a Select dropdown field in Sencha Touch

Does anyone know how to change the default image of a select dropdown in Sencha Touch to a customized image? I've attached a screenshot for reference but can't seem to find any properties or classes to adjust this. Any guidance would be greatly a ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

Dealing with popups in nightmarejs: what's the best approach?

Looking for guidance on managing website pop-up windows in nightmarejs. Specifically interested in tasks such as viewing a list of open windows, closing them, extracting data from the pop-ups, and potentially subscribing to popup creation events. Your ins ...

Disallow users from altering tokens in the input field

Is there a way to use JavaScript or jQuery to prevent specific elements or tokens within a textarea from being changed? For example, consider the following text in an input: this is normal text {this can't be changed 1}. This is more text. {This c ...

The functionality of bigvideo.js is not supported on the Opera browser

I am facing an issue with the bigvideo.js script as it does not seem to be working on the Opera browser. Do you have any suggestions for a solution? I successfully used this script in Firefox. $(function() { var BV = new $.BigVideo({useFlashForFirefo ...

What is the method for setting required to true only when the user meets a specific condition?

Hello, I am creating models for my mongodb. I want the birthday field to be required only if the user being added is a student. If the user is a teacher, it is okay if no birthday is provided. const userSchema = mongoose.Schema({ 20 21 _id: m ...

Retrieve the username from a JSON Web Token in an Express application

I am working on a project that involves 3 different routes in my code - Users, Products, and Orders. Using jwt, I generate tokens for users and need to assign orders to token owners. Below is the Order Model I am using: var mongoose = require('mongoo ...

The previous successful execution of req.body is now yielding an undefined value

My req.body is suddenly undefined, even though it was working fine a few days ago. I've tried using the deprecated body-parser module, but no luck. Here's my code: JS: var express = require("express"); var router = express(); require(& ...

JSON input unexpectedly ended after an HTTP request was made

During a HTTPS request, the JSON response is stored in the data variable. While this function has worked correctly in other parts of the program, I am now encountering a SyntaxError: Unexpected end of JSON input when trying to parse the data using JSON.par ...

Preventing a user from inputting a value below 1 in a number input field within Vue 3

I'm working on implementing a number input field in Vue 3 that restricts the user from entering a value less than 1. Currently, I have set the minimum value to 1 to prevent using the input arrows to go below 1: <input min="1" type="n ...