Utilizing JavaScript to employ the indexOf function on arrays in MongoDB

In my script, I have an array outside mongodb called title. The dataset in mongodb contains fields that I do not want to include (Dataset_1). I am using an indexOf function to match values and create a ranking.

The structure of Dataset_1 is as follows:

geotype    state            numbers    
state      Alabama          14
state      Alaska           344
state      California       144
state      New York         255
state      Washington       233
state      Guam             255
state      Puerto Rico      36
state      Virgin Islands   366
state      Delaware         434
state      New Mexico       444
state      Maryland         544
...

The var title array looks like this:

var title = [            
'Alabama',         
'Alaska',           
'California',       
'New York',         
'Washington',       
'Delaware',         
'New Mexico',       
'Maryland'
...]         

It's important to note that var title only contains US states, not territories.

My objective is to rank the states by 'numbers' in a new column 'ranking' if there is a match with the title array. Territories like Guam and Puerto Rico should not be ranked.

if (Dataset_1[column].indexOf(title) > -1) {
    execute 
}

Below is the code I am using to create rankings using javascript with mongodb dataset update:

//This script includes var title as well
var rank = 0;
var rank_value = Infinity;
db.Dataset_1.find({'geo_type': 'state'}).sort({'numbers': -1}).forEach(function(doc){
    if (doc['state'].indexOf(title) > -1) { 

    if (doc['numbers'] < rank_value) {
        rank_value = doc['numbers']; 
        rank = rank + 1;
    }
    if (doc['numbers'] != null) {
        db.Dataset_1.update({
            '_id' : doc['_id']
        },{$set: {
            'ranking' : rank
        }})
    }
    }
});

However, this code ranks all the fields instead of only the matches. Am I using the indexOf function correctly?

I have experimented with different ways to solve this issue, but I either encounter syntax errors or include unwanted fields.

To summarize, here is an example output:

geotype    state     numbers    ranking
state      Alabama   14         11
state      Alaska    344        5
...

Answer №1

The issue lies in the following code snippet:

if (Dataset1.indexOf(title > -1)) {
    execute 
}

A corrected version should be:

if(Dataset1.indexOf(title) > -1)

UPDATE:

If you need to verify if the state is within a list of titles, the correct approach would be:

if(title.indexOf(doc['state']) > -1)

instead of

if (Dataset1.indexOf(title) > -1)

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

Creating two tables in JavaScript and styling them with separate CSS designs

I am in the process of creating two tables dynamically using JScript. Instead of using the traditional method of separating them with assigned tags in HTML, I have approached the creation of the first table in a different way: function makeCells() { v ...

Is there a way to navigate to a newly created document?

Is there a way to automatically redirect a user to the show action of a document or post they have just created using express.js? Take a look at the following code snippet, which outlines how I am creating the document: app.post('/document/create&ap ...

A guide on utilizing Puppeteer for capturing screenshots of web pages with embedded videos

Currently, I am using Puppeteer to access a website and capture a screenshot of a video. Unfortunately, the default Chromium browser that Puppeteer uses does not support certain video types. I have managed to get it working by launching Puppeteer with a l ...

Utilizing the indexOf Method in AngularJS

Here is my array: emp=["111","56"]. This is the code I have: <input type="text" placeholder="Enter" class="form-control" name="Emp" ng-model="myModel.Emp" ng-required="currentStep ==2"/> <input type="text" placeholder="Enter" class="form-contro ...

What is the reason for `then` generating a new promise rather than simply returning the promise that was returned by `

I've been curious about why, in a situation where the onFulfilled handler of then() returns a promise p2, then() creates a new promise p3 instead of simply returning p2? For example: let p1 = new Promise(function(resolve, reject) { resolve(42); ...

Using Ajax to send a variable to PHP and then selecting data from an SQL database

Currently, I am facing an issue where I need to pass a variable to my "fetch" PHP file. In the fetch.php file, I execute a query to a MySQL database with certain parameters. However, I have hit a roadblock in the process. I am able to retrieve the variab ...

What is the process for adding a line of JavaScript directly into the code (instead of using an external .js file)?

I am trying to insert a script tag that will run one line of JavaScript directly into the head of a document instead of inserting an empty script tag with a src attribute. So far, I have the following code: <script type="text/javascript"> var script ...

Tips on how to update the styling of an active link

http://jsfiddle.net/G8djC/2/ Looking to create a tabbed area where content changes based on the tab clicked. The Javascript function switches the link class to active upon clicking. However, struggling to change the color of the active tab beyond the firs ...

Listening for an event or using a CSS pseudo-class to detect when the scrollbar becomes

Are there any JavaScript event listeners or CSS pseudo classes that can detect when a scrollbar appears and disappears? For example, on Mac OS and Windows Internet Explorer 10 or newer, the scrollbars are hidden by default but appear when scrolling begins. ...

What is the proper method for incorporating a Greater-than symbol within a jsx tag?

I am attempting to display a Greater-than sign '>' inside of a button using material-ui with react, but I am receiving a parsing error. Is there a simpler way to achieve this without writing lengthy code? <Button onClick={includeOperator(& ...

Clear previously filtered items

I am currently working on implementing a search functionality using Javascript for my project, but I've hit a snag. After hiding certain items, I'm having trouble making them appear again. JSFiddle The code I have so far is as follows: $(' ...

Understanding the repetition of the X axis in Recharts for ReactJS

I am facing an issue where the X axis on my graph is repeating three times for each month of the year. I have tried adding my data, but the duplication persists. Can anyone provide insight on how to correct this error? What am I doing wrong? Below is a mi ...

Modifying the CSS properties of elements with identical IDs

Encountering an issue while attempting to modify the CSS property of elements with similar IDs using JavaScript. Currently, running a PHP loop through hidden elements with IDs such as imgstat_1, imgstat_2, and so forth. Here is the code snippet being emp ...

Issues have been reported with the functionality of the backbone.js app when switching views, particularly regarding the inconsistent

I am in need of assistance with backbone.js. Whenever a 403 or 401 error occurs, I want to display the login view. Currently, I have attempted the following approach: $(document).on('ready', function(){ app.loadTemplates(['ShellView&apo ...

Ajax/PHP - unrecognized value in autofill

I have implemented this particular example to execute an ajax data query from a MySQL database, which returns a table. Currently, this setup functions correctly when text is manually entered into the input form. Example: https://i.sstatic.net/TTgLz.jpg T ...

Encountering issues with the routing in my live Node.js project: ERROR

I am encountering issues with my project in production. I suspect it could be due to a misconfiguration or something similar. Could you please review the provided code snippets and see if you notice any potential issues? The project works fine locally, bu ...

Tips for customizing the blinking cursor in a textarea

I am experimenting with creating a unique effect on my website. I have incorporated a textarea with transparent text overlaying a pre element that displays the typed text dynamically using JavaScript. This creates an illusion of the user typing in real-tim ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

Does GIF animation operate on the same thread as JavaScript in all popular web browsers?

When my AJAX request is in progress, an animated GIF is displayed to show activity. However, I have noticed that the animation freezes while the response from the request is being processed by a script that heavily updates the DOM. After researching this ...

"Concealed beneath the text is the link to return to the

I have implemented a back to top link in my MVC project. Layout: <a id="back-to-top" href="#" class="btn btn-primary btn-lg back-to-top" role="button" title="Click to return to the top of the page" data-toggle="tooltip" data-placement="left"><spa ...