Discover records that include the specific object id within an array (Mongodb)

I'm currently tackling a node project and struggling with using the find() function on an array of object ids.

Let me share an example of a document stored in my mongodb database:

{
  "_id": {
    "$oid": "6515923586714e6ae70be0a9"
  },
    "managers": [
    {
      "$oid": "6515a0ba76e7e07f68160ef5"
    },
    {
      "$oid": "6515a0d35c2d7cad9b070e64"
    }
  ]
}

This is the code snippet I've tried:

router.get("/processes/formanager/:id",async(req,res) =>{
  let processCollection = await db.collection("processes");
  let query, processes, cursor;

  try{query = {"$elemMatch": new ObjectId(req.params.id)};}
  catch(err){res.status(404).json({error: "Not a valid id"}); return;}

  try{
    cursor = await processCollection.find({managers: query});
    
    // iterate over cursor once
    processes = await cursor.next();
  }
  catch(err){
    console.log(err);
    res.status(404).json({error: "No processes assigned to this manager"}); 
    return;}
  res.status(200).json({ processes })

});

My expectation is to retrieve this document along with others that meet the specified criteria. In case the first result is obtained, I will proceed to iterate over the cursor.

However, upon running the code as is, I either encounter null processes or receive the error message, "$elemMatch needs an object" when I remove the quotes around $elemMatch.

Answer №1

If you want to search through an array of basic values (not array, not object), you can simply execute the following query:

query = {"managers": new ObjectId('6515a0ba76e7e07f68160ef5')};
cursor = await processCollection.find(query)

For searching through an array of objects, you need to utilize $elemMatch. Check out the example below:

// example data
[
    {
        _id: '6515a0ba76e7e07f68160ef5',
        name: "John",
        surname: "Doe"
    },
    {
        _id: '6415a0ba76e7e07f6816a125e',
        name: "Alex",
        surname: "Gerard"
    }
]

query = {"$elemMatch": {_id: new ObjectId('6515a0ba76e7e07f68160ef5')}};
cursor = await processCollection.find({managers: query})
// or
query = {"$elemMatch": {name: "Alex"}};
cursor = await processCollection.find({managers: query})

Answer №2

My coworker shared the accurate code with me

  1. Avoid putting $elemMatch / $in in quotation marks
  2. For my situation, the query within $elemMatch / $in needed to be enclosed in angled brackets []

cursor = await processCollection.find({managers: {$in:[new ObjectId(req.params.id)]}})

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

The unique identifier for a Python object

In Python, I am interested in creating an object ID. Here's what I have in mind: While I am aware of databases like MySQL, SQLite, MongoDB, etc., I want to create an object ID for storing data in JSON format. Previously, I used to insert JSON inform ...

Incorporating FaceBook into a PhoneGap Application

Currently, I am working on integrating Facebook into my phonegap/cordova application. To guide me through the process, I am using the resources provided in this link: https://github.com/davejohnson/phonegap-plugin-facebook-connect/ Even though I have bee ...

Error message: "Unable to locate module for split-pane-react in Jest"

Attempting to run Jest tests on my component with [email protected] in a Next.js project using typescript. Encountering the following error: Cannot locate module 'split-pane-react' from 'my component path' when running the test ca ...

What is the correct way to add a period to the end of a formatted text?

Hello, this marks the beginning of my inquiry. I apologize if it comes across as trivial but I have come across this piece of code: function format(input){ var num = input.value.replace(/\./g,''); if(!isNaN(num)){ num = num.toString ...

Executing Statements in a Specific Order with Express and Sqlite3

I am having an issue creating a table and inserting an item into it using the node command. Despite my efforts to reorganize my script, the item is being inserted before the table is created. Interestingly, manually inputting the commands in sqlite3 works ...

Step by step guide on uploading files using Vue.js and Express.js

Hello there, I am new to Vuejs and Express and I'm looking to practice my skills. Currently, I am attempting to build a User Profile with an image upload feature using Vuejs and ExpressJs but unfortunately, none of the files or text are uploading as ...

Is there a way to send a promise resolve or reject from a function code within router.post() in Express?

Below is my code in express (node.js) router.post('/example.json', function (req, res) { // getFileInfo is a function to return an array return getFileInfo(req.body.fileList).then((array) => { axios({ method: 'post', ...

Exploring Entries in Several JSON Arrays

In my current project, I have successfully generated JSON using JSON-Simple. Query: I am seeking guidance on how to extract specific elements like "Sentiment," "score," and "review" from this JSON array. Although I have referred to a helpful resource he ...

Seeking assistance with establishing connections and inserting information into a mongodb database

I'm seeking guidance on mongodb. Recently, I began using it and created a Cluster named db, with a database called discord-bot containing a collection named users The objective is to create a database entry for each user. Below is the code I've ...

Having difficulty retrieving the current time of an audio element using jQuery

Currently, I am facing an issue while attempting to manage an audio element for my custom player. Despite numerous attempts, I have been unsuccessful in acquiring the currentTime and duration properties. Below is a snippet of what I've tried: var pla ...

What sets apart the use of `function(){}.bind(this)` and `angular.bind(this, function() {})`

Can you highlight the difference between these two code snippets? function Ctrl($scope) { $scope.$watch(function() { return this.variable; }.bind(this), /*...*/); } and function Ctrl($scope) { $scope.$watch(angular.bind(this, functio ...

Managing API calls through Next.js routing

Here is a next.js handler function for handling api requests on our server. I am looking for assistance on how to access a variable between request methods. Any help would be greatly appreciated. export default function handler(req, res) { if(req.met ...

How to retrieve nested document counts in Mongoose?

I need help retrieving the total conversation count for each agentid, but I'm experiencing difficulties. Let me explain the scenario. There are 2 supports from 2 different agents. Each support has 3 and 5 conversations, respectively. Currently, the r ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

Organizing textual maps within a 2D array for rendering on an HTML5 Canvas

In my spare time, I am working on creating an HTML5 RPG game. The map is implemented using a <canvas> element with specific dimensions (512px width, 352px height | 16 tiles across, 11 tiles from top to bottom), and I'm wondering if there's ...

Tips for updating specific properties of an object within a MongoDB database using arrays

I have encountered a problem with updating only specific properties of an object in my MongoDB database. While the query I'm using is working for most variables, it unexpectedly sets certain arrays (media: [] and sports: []) in the athleteProfile back ...

Can you explain how to use a toggle switch to make a select dropdown select a random option?

Currently, I am in the process of setting up a page for a character generator. Users will have the option to randomize traits or input their own. The interface includes toggle switches for the "choice vs random" options for each trait category, as well as ...

Looking to deactivate a particular checkbox in a chosen mode while expanding the tree branches

I encountered an issue with a checkbox tree view where I needed to disable the first two checkboxes in selected mode. While I was able to achieve this using the checked and readonly properties, I found that I could still uncheck the checkboxes, which is no ...