using javascript objects to query mongodb/meteor collections

Linked to: mongodb/meteor collection check if subdocument field exists when field is a variable

I am attempting to perform a query on a Meteor collection by constructing an object with dynamic field names. This method works when the object has a single field, as shown below

var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query); //works fine

However, I need to query with multiple criteria. For instance, I need to verify the presence of a field with a variable name, along with checking if another field equals true, and if yet another field equals a variable. I am trying to create a general approach to building query objects. I have attempted the following:

var query = {};
query['myField.'+myVariable] = {$exists: true};
query[newField] = false;
Collection.find(query);

This approach does not yield the desired results. I suspect this may be due to 'newField' not being an Object type or some other reason.

I also tried using the $and selector, but my syntax might not be correct...

var query = {};
var object = {};
object['myField'.+myVariable] = {$exists: true};
query['$and'] = [object, {newField: false}];
Collection.find(query);

Unfortunately, this approach also leads to issues. I was attempting to utilize the mongo $and selector, which requires an array.

How can I construct a Meteor collection query using JavaScript object notation and object literals? I believe one of these methods should work.

To elaborate, I am seeking something similar to the following (partly pseudocode due to the limitations of dot notation in a mongo query)

Collection.find({correlated: false, readBy.(Meteor.userId()): {$exists: true} ...)

I also thought the following should work:

var query = {};
query['myField.'+myVariable] = {$exists: true};
Collection.find(query, {otherField: false}) 
//OR 
var query2 = {};
query['priority'] = false;
Collection.find(query, query2)

However, neither of these approaches yield the desired results.

EDIT: Example document - I wish to find a document where the current user ID is NOT listed in the readBy field AND correlated is set to false

{
    "_id" : ObjectId("55b6868906ce5d7b1ac6af10"),
    "title" : "test",
    "correlated" : "false",
    "readBy" : {
        "DXqLhesDEJq4ye8Dy" : ISODate("2015-07-27T18:29:43.592Z")
    }
}

Answer №1

It is important to note that when using the find method, only one selector argument is allowed. For example:

Collection.find(query, {otherField: false})

This code snippet is not accurate because the query parameter must include the information for otherField. Take a look at the following code snippet for a better understanding:

// 'readBy.abc123'
var key = 'readBy.' + Meteor.userId();

// Constructing the selector using different parts
var selector = {correlated: false};
selector[key] = {$exists: false};

// The selector will resemble something like:
// {correlated: false, 'readBy.abc123': {$exists: false}}
// Remember, these conditions are combined with AND, so all must be true

// Use this cursor to retrieve your documents
var cursor = Collection.find(selector);

// Print out one of the selected documents
console.log(Collection.findOne(selector));

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

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

Is it beneficial to rotate an image before presenting it?

I am looking for a way to display a landscape image in portrait orientation within a 2-panel view without altering the original file. The challenge I am facing is that the image size is set before rotation, causing spacing issues with DOM elements. Is ther ...

Guide on extracting HTML content from JSON and displaying it in a UIWebView (utilizing Swift 3.0)

Can anyone guide me on how to use JSON2HTML to parse HTML data from JSON and display it in an UIWebView using Swift 3.0? Your help is much appreciated! This is what I have attempted so far: let jsfile1 = try!String(contentsOfFile: Bundle.main.path(forRes ...

Automatically submitting the selection when it changes

I am facing an issue with a selection form that is supposed to update the database on change using jQuery, but it seems like nothing is happening. Can anyone provide assistance with this problem? <SELECT name='status' id='status'> ...

Using regular expressions to eliminate text located outside of the tags within a string

Presented is a string consisting of an XML string below: var xmlString = "<str>rvrv</str>rvrv<q1>vrvv</q1>vrvrv<q2>rtvrvr</q2>"; I am seeking assistance on how to eliminate text that lies outside the tags (text no ...

What is the best way to transfer the window object from the current tab to the extension?

I am looking to retrieve user storage data (local and session) from a specific tab, similar to what is shown in this app (see screen below). From my understanding, I need to access the window object of the active tab. While I have obtained the object, I a ...

When using jQuery, remember to encode square brackets in order to target specific

Imagine an input element <input id="meta[152][value]" type="text" /> In this case, the input field is created on-the-fly. I must choose that particular field. That's why I used, alert($('#meta[152][value]').val()); However, it appe ...

The design of Foundation's 4 form dropdown is not displaying correctly on Internet Explorer versions 8 and below

During the development of a website using Foundation 4 framework, I encountered an issue with form dropdowns not displaying correctly on Internet Explorer 8 and older versions. Instead of using Foundation's javascript rendering, they appear as the def ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

Detecting errors on the client side with JSON payload in Next.js and a personalized server

Working with Next.js and a custom Express server, I've encountered an issue regarding basic API error handling. I have set up a simple error handling middleware that looks like this: app.use((err, req, res) => { res.status(400).send(message); ...

Pressing the Enter key does not initiate a redirect on the page

Hey there! I've set up a text field where users need to input a password in order to download a PDF file. If the password is correct, they are directed to the URL of the PDF file. However, if the password is wrong, they are redirected to a page called ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

Displaying information from an array in a view and manipulating it using JavaScript

Having trouble displaying array data in a customized way. Here is how my array structure looks: array:2 [▼ "folder1" => array:5 [▼ 0 => "4.png" 1 => "2.png" 2 => "1.png" 3 => "3.png" 4 => "5.png" ] "folder2" ...

Maintaining duplicate values in a JSON stringify operation: Tips for retention

Server responses are being received in JSON format, which may contain objects with duplicate keys. When displaying the results, I noticed that only the last value for duplicate keys was showing up. After investigating, I realized this was due to using the ...

Launch a new Windows form upon clicking an HTML button using DotNetBrowser

I attempted to open a Windows form using the DotNetBrowser control with specific HTML content as shown in the code below. Upon clicking a button on the HTML page, I want to hide the loaded form and then display the second Windows form. Here is the C# cod ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

Is there a more efficient method for streamlining the Express-Validator middleware in a separate file

In my current project, there is a lot of validation required using Express-Validator. In each file, I find myself repeating the same validation code: //Validation and Sanitizing Rules const validationRules = [ param('tab').isString().isLength({ ...

Rearranging a JSON Object post editing

Currently, I am working on a project where I need to display and sort a list of items based on a JSON object. This includes sorting by both string values and integers within the object. So far, I have been successful in listing and sorting the items by st ...