MongoDB function error: Variable is not defined

I'm feeling a bit lost here. I'm attempting to search for documents using the $function operator, as outlined in this S_function documentation.

Here is my model:

const newsSchema = new mongoose.Schema({
news_id: {
    type: mongoose.Schema.Types.ObjectId,
    unique: true,
    index: true
},
created_at: { type: String, default: Date.now().toString() },
updated_at: { type: String, default: Date.now().toString() },
Company_id: [{type: mongoose.Schema.Types.ObjectId}],
Stock_id: [{type: mongoose.Schema.Types.ObjectId}],
newsItem: {
    date: {type: String},
    title: { type: String },
    summary: { type: String },
    url: { type: String, unique: true },
    content: { type: String }
}
};

This is my code attempt:

newsModel.aggregate([
        {$match: {$function: {
            body: matchArrToArr(matchArr, Company_id),
            args: [ "$Company_id" ],
            lang: "js"
         }}}
    ])

The variable matchArr comes from the surrounding function and Company_id is supposed to refer to the array 'Company_id' from the news document. However, upon executing the function, I receive an error stating 'Company_id is not defined'. It makes sense because I never define it. How can I properly reference the Company_id field within the function?

I also attempted using find($expr:{$function:... with no success, as well as $where:... with this.Company_id. In the first case, I received the same error. In the second case, 'this' refers to the state of my calling JavaScript function rather than the DB document.

My goal is to retrieve all documents where one of the IDs in the Company_id array matches one of the IDs I provide. If there's a more efficient way to achieve this without using $function, I'm open to suggestions. However, I'm also keen on understanding what I may be doing wrong with my $function expression.

Thank you!

Answer №1

Here is the solution you are looking for:

let targetCompany_id = "60278ce8b370ff29b83226e7";

db.news.find(
    {
        $expr: {
            $function: {
                body: function(company_ids, targetCompany_id) {
                    let _ids= company_ids.map(company_id => company_id.valueOf());
                    return _ids.includes(targetCompany_id);
                },
                args: ["$company_id", targetCompany_id],
                lang: "js"
            }
        }
    }
)

However, a simpler alternative exists:

db.news.find({ 
    company_id: {
        $in: [targetCompany_id]
    }
});

Considering this easier method, why do you wish to use a function?

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

Establish a secure connection tunnel using ngrok to connect to a local MongoDB database

Looking to establish a connection tunnel between two computers. Computer 1 : Frontend (React) Computer 2 : Backend API with MongoDB local database and NodeJS server We attempted to use ngrok for creating the tunnel so my partner can test/build a connect ...

When requesting a Node.js API from Javascript fetch, the session custom property is throwing an undefined error

I am currently working on a User Login Project, where the APIs are built using Node.js and Express. The UI part is developed using HTML and JavaScript, with these components existing as separate projects. Upon user login, a fetch call is made in JavaScrip ...

Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them. If you want to check out my curren ...

body-parser: unable to retrieve data from the form

I'm struggling to fetch values from a form using body-parser in my user sign-up feature. The console keeps printing 'undefined' which is baffling me. I even attempted using Postman, but no luck there either. Here's the snippet of my cod ...

Having trouble deserializing a MongoDB collection with polymorphism in a Spring Boot application

My database has a collection called "items" that contains different types of jewelry. Each document in the collection has a property called "category," which I'm using to deserialize the documents into separate classes such as Pendant, Ring, etc. usin ...

Is there a way to combine two addEventListeners into one for a single click event?

preview of a to-do list app I am faced with a situation where I have two addEventListeners, one to change the text color and another to change the circle color. In Condition 1: When I click on the circle, both the text and circle colors are changed. In ...

Ways to compel a JSON-transmitted expression into the Angular scope

Seeking guidance on the best way to convert HTML from JSON into a trigger for a modal/toggle upon clicking. Within the JSON data consisting of 100 entries, there are about 10 links that need to activate a pop-up when clicked. These links are displayed as ...

Effect triggers the swapping of div elements

Is there a way to prevent these divs from shifting positions following an effect? To see the issue, please visit this fiddle: https://jsfiddle.net/d1gxuLn8/1/ View full screen result here: https://jsfiddle.net/d1gxuLn8/1/embedded/result/ ...

An error was encountered when attempting to use the 'await' syntax in a useEffect() function that called axios.get()

To avoid using .then(..), I have switched to utilizing await. I am making a call to a function that includes an Axios request and returns the data as response.data after awaiting for it. My functional component has a useEffect that is meant to initialize a ...

What is the best way to integrate an asynchronously initialized API with a Vuex state?

As I delve into the world of Vue + Vuex, I find myself grappling with the challenge of initializing an API that relies on asynchronous methods. The common solutions I've attempted so far have hit roadblocks - can't use await outside an async fun ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

What are the recommended Official Docker Image(s) for deploying an application with numerous dependencies?

In the process of deploying my Ruby on Rails web application with Docker containers, I have identified the following dependencies: Ruby(v2.3.1) RVM MongoDB (This will eventually run in its own container) Nginx Initially, I started with the official cen ...

I'm encountering difficulties in utilizing Ajax to upload images

I have been attempting to utilize ajax and bootstrap (modal) to add a new product. However, when I click the save changes button, I encounter an issue where all fields return an error message stating 'Undefined index'. Below is the code snippet ...

Display only the objects in an array that match a specific value in MongoDB

Here is my current MongoDB Schema for the userTask: const userTaskSchema = new mongoose.Schema( { {...}{..}{...}{..} //Multiple objs above here, I'm specifically seeking assistance with the userTasks userTasks: [ // Arr ...

What is the best way to modify a large portion of JSON data in a nodejs environment?

I am currently working with two separate JSON files - data.json and dataForUpdate.json The contents of data.json are as follows: [{"name": "test", "isDefault": true, "settings": { "type": "Separation", "scanner": { "brightness": 0 ...

Transmit an array to a PHP script in WordPress using Ajax

I am attempting to pass an array from a JavaScript file to a PHP file on the server, but I am encountering difficulties when trying to access the array in PHP. Below is the function in my JS file: var sortOrder = []; var request = function() { var js ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

Adjust the position of a textarea on an image using a slider

Currently, I am exploring how to creatively position a textarea on an image. The idea is to overlay the text on the image within the textarea and then use a slider to adjust the vertical position of the text as a percentage of the image height. For instanc ...

Grabbing an AJAX Request

Currently, I am working on a Firefox extension that is designed to analyze the HTML content of web pages after they have been loaded in the browser. While I have successfully captured events like form submissions and link clicks, I am facing an issue wit ...

Broken Mui Input - Full width with attributes for minimum and maximum values

I've created a sandbox to demonstrate an issue I came across that seems unbelievable, but it's happening. Here's the link: https://codesandbox.io/s/nifty-swanson-yxj4n2?file=/NumberField.js:1075-1097 The problem is simple - when both the ht ...