Is there a way to retrieve documents from mongodb by querying for documents whose ids are stored within the array variable `ids` using the $in operator

Can someone help me with querying all documents based on IDs from an array passed to my code via user input?

var attackersIds = fights[i].attackersIds;
attackers = cardsCollection.find({"_id" : { "$oid" : { $in: attackersIds } } });

However, I encountered an error:

MongoDB: Can't canonicalize query: BadValue unknown operator: $oid

I tried resolving it by using ObjectId(...) as follows:

var attackersIds = fights[i].attackersIds;
for(var a=0; a<attackersIds.length; a++){
    attackersIds[a] = ObjectId(attackersIds[a]);
}
attackers = cardsCollection.find({"_id" : { "$oid" : { $in: attackersIds} } });

But now I'm getting another error:

ReferenceError: \"ObjectId\" is not defined.

This seems to be due to an older version of node.js that I can't upgrade because of limitations imposed by my server provider.

So, how should I go about querying MongoDB for documents whose IDs are in my var attackersIds array?

Here are some sample documents:

{ "_id": { "$oid": "567ee17ae4b0128ba4ce9049" }, "classId": 9, "name": "Recruit", "description": "", "type": "creature", "cost": { "yellow": 1 }, "attack": 1, "defense": 0, "hp": 1, "area": "field1", "playerId": "56590c7ce4b03fe0cf20842d" }
{ "_id": { "$oid": "567ee17ae4b0128ba4ce904a" }, "classId": 1, "name": "Farm", "description": "", "type": "building", "cost": {}, "attack": 0, "defense": 0, "hp": 5, "generatesMana": { "yellow": 1 }, "area": "hand", "playerId": "56590c7ce4b03fe0cf20842d" }
{ "_id": { "$oid": "567ee17ae4b0128ba4ce904b" }, "classId": 1, "name": "Farm", "description": "", "type": "building", "cost": {}, "attack": 0, "defense": 0, "hp": 5, "generatesMana": { "yellow": 1 }, "area": "hand", "playerId": "56590c7ce4b03fe0cf20842d" }
{ "_id": { "$oid": "567ee17ae4b0128ba4ce904c" }, "classId": 9, "name": "Recruit", "description": "", "type": "creature", "cost": { "yellow": 1 }, "attack": 1, "defense": 0, "hp": 1, "area": "deck", "playerId": "56590c7ce4b03fe0cf20842d" }

Answer №1

Consider rearranging the order of $in and $oid

"_id": {
        "$in": [
            {
                "$oid": "54651022bffebc03098b4567"
            },
            {
                "$oid": "54651022bffebc03098b4568"
            }
        ]
   }

If your situation calls for it, you may require a small helper function to convert an array of ids into an array of objects with a $oid field.

attackers = cardsCollection.find({"_id" : { "$in" : attackersIds.map(function(element){
    return {
        "$oid": element
    });

Answer №2

Transforming the attackersIds array into an array of ObjectId type is key. The process will vary depending on the package you're using to interact with your mongodb collection.

If you're using mongojs:

var mongojs = require('mongojs');
for(let a=0; a<attackersIds.length; a++){
    attackersIds[a] = mongojs.ObjectId(attackersIds[a]);
}

If you're using mongodb:

ObjectID = require('mongodb').ObjectID;
for(let a=0; a<attackersIds.length; a++){
    attackersIds[a] = new ObjectId(attackersIds[a]);
}

Once converted, focus your query on _id:

attackers = cardsCollection.find({"_id" : { $in: attackersIds } });

Answer №3

If you want to convert to an objectid, use this method:

mongoose.Types.ObjectId(inputString)

Just make sure 'mongoose' is your mongoose variable:

var mongoose = require('mongoose')

Alternatively, you might not need to do this step:

CardsCollection.find({_id:{$in:attackersids}})

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 verify the file extension in a multi-input form during an upload process?

I am looking for a solution that requests users to upload 4 different files when filling out the form. Check out this example of one of the inputs: <div class="custom-file"> <input type="file" class="custom-file-input" accept="video/*" id="v ...

I am unable to get the Javascript code `window.print()` to function

I tried creating a basic link to print a page on my website using Google Chrome, but for some reason, the link is not working. Upon checking my console log, I noticed an error message that says: Maximum call stack size exceeded Here is the HTML code I us ...

Error: Attempting to access a property of an undefined value (referencing '8') was unsuccessful

Hello everyone, I am new to posting and identify as a junior Frontend developer. I'm encountering a confusing issue with the InputLabel from Material UI (ver. 5) on a specific section of the website I'm working on. On the homepage, I successfully ...

Having trouble with adding a listener or making @click work in VueJS?

Apologies for my limited experience with Vue. I am currently facing an issue where one of my click functions is not working as expected for multiple elements. The click event is properly triggered for the #app-icon element. However, the function is not be ...

Code-based document editing with CouchBase

To test Couchbase, I need to create a servlet that will edit 1,000 JSON documents by changing the value of '"flag": false' to '"flag": true'. How can I achieve this task? Here is my view code for finding documents with '"flag": fa ...

Addressing React Native Rendering Problems

I'm currently working on a weather application and facing some challenges with rendering the forecast. I'm uncertain whether it's related to the styling. I've tested the API call through the browser and encountered no errors in Android ...

Searching for an element with a changing name using jQuery - Struggling with quotes

Looking to navigate my DOM based on the value of an option in a select box. The value of "searchkey" can vary based on user input, for example: searchkey = dell'anno searcheky = dell"anno These options, particularly the first one, can cause issues ...

Transferring extensive PHP variables to JavaScript

After checking out different strategies for passing data from PHP to Javascript like this and this, I have concerns about the memory and variable size limits in javascript. Currently, I am transferring large chunks of HTML from PHP to Javascript to dynami ...

What is the process for retrieving information from a particular section of a Wikipedia page with the help of the Wikipedia API?

I am currently working on creating an android app and I am in need of extracting the Nutrients section of a specific vegetable or fruit from Wikipedia to display in my app. https://i.sstatic.net/avaGA.png This is my progress so far... I am attempting to ...

Whenever I attempt to connect to Stripe, my code fails to execute properly

My knowledge of Javascript is limited, but I have a basic understanding. I am currently diving into learning about Stripe and testing it in a local environment with a Wordpress install. Following the Stripe documentation, I have successfully installed Node ...

Tips for transferring POST body data to a different route without losing any information

Assuming I have the following route: app.post('/category',function(req,res){ res.redirect('/category/item'); }) In this scenario, the user will submit data to the '/category' route and then automatically be redirected ...

Restrict the hide/show functionality on a div to only operate within its specific radio group, without impacting the other radio groups within the form

I created a form with 3 radio groups that show different sets of divs based on the selection made. The issue I'm facing is that the current code hides radio content divs across all 3 radio groups. How can I fix this? My goal is to display all "Yes" c ...

Framer motion layout animation fails to account for page scrolling during transitions in NextJs routes

Currently, I am working on a fascinating NextJS project that showcases a series of interactive blocks. As the user navigates through the app, these blocks dynamically adjust their size and position on the screen. To achieve this effect, I'm leveragin ...

Tips for securely transmitting data via a hidden form using the POST method

I have a query that displays records of people, and I want to send the id_Persona using a hidden form through a post function to the idsPersonas.php page. However, when I try to do this, it redirects me to an undefined page. Here is the code snippet: < ...

Trouble with activating dropdown toggle feature in Bootstrap 5

I recently upgraded to Bootstrap 5 and now my code is not functioning properly. <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria- controls="navbarCollaps ...

What steps can I take to maximize the efficiency of my code for optimal performance?

I am working on speeding up my code for improved performance. The snippet below is a part of the code responsible for extracting data from a website, identifying specific values, and then displaying them using console.log. My objective is to optimize this ...

Changing from Basic to JavaScript?

Good evening, I am looking to convert this example code from Basic to JavaScript. Since JavaScript does not support the "Go To" command, I would appreciate it if you could help me with the translation. Thank you in advance. 10 x = 1666.66 20 y = 1.007897 ...

React state is not refreshing as expected

I am having trouble updating the state with new employee data. The push function is not inserting the new employee data into the state. In the addPar function, I set up a console log and it shows that the data is there, but it fails to push it to the sta ...

having difficulty making changes to a subdocument within an array

Struggling to update the value for uid in solts.slots but nothing seems to be working. I aim to iterate two levels of an array to modify the document. { "_id": { "$oid": "638455dee12f0122c9812697" }, "bid": "6 ...

Receiving a blank array upon calling res.json() in Node.js script

I'm facing an issue with my code snippet that displays all posts, including the username and display picture of each user. Everything seems to be working fine as the log output is perfect. However, I'm struggling to return this data as a JSON obj ...