Searching for an item in an array within MongoDB: Tips and techniques

I am attempting to locate the object containing a specific element within an array:

Here is my query:

router.get('/', function(req, res) {
    var userSubscribed = req.user.email;
    db.posts.find({ "SubscriberList": { $elemMatch: userSubscribed}}, function(err, object){
        if (err) console.log(err);
        else console.log(object);
        res.render('index', { title: 'Home', user: req.user});
    })
});

The error message displayed is as follows:

{ [MongoError: Can't canonicalize query: BadValue $elemMatch needs an Object] name: 'MongoError'}

An example of an object in the database:

{ 
    "_id" : ObjectId("5490afa8416841105626cc41"), 
    "post" : { 
        "title" : "Ralph", 
        "category" : "Node", 
        "date" : "2014-12-11", 
        "description" : "Node coming soon!" 
    }, 
    "owner" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1838e9492808c9380cf93808d9189a1868c80888dcf828e8c">[email protected]</a>", 
    "status" : "active", 
    "category" : "Node", 
    "SubscriberList" : ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0919c91829993b0989f849d91999cde939f9d">[email protected]</a>" ]
}

Answer №1

When dealing with an array of strings like the SubscriberList, there's no need to use $elemMatch unless you're trying to match multiple properties within a single array element.

To find posts where a user is subscribed, you can simply query:

router.get('/', function(req, res) {
    var userSubscribed = req.user.email;
    db.posts.find({ "SubscriberList": userSubscribed }, function(err, object){
        if (err) console.log(err);
        else console.log(object);
        res.render('index', { title: 'Home', user: req.user});
    })
});

Answer №2

Give this code a shot:

router.get('/', function(req, res) {
var userSubscribed = req.user.email;
db.posts.find({owner:userSubscribed}, function(err, data){
    if (err) console.log(err);
    else console.log(data);
    res.render('index', { title: 'Home', user: req.user});
})
});

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

Detect the element that initiated the AJAX call in Jquery event handling

My goal is to capture the beforeSend event for all form submits on my site without interfering with jquery.unobtrusive-ajax.js. I've attempted the following method: $(document).on("ajaxSend", function (e, request, settings) { console.log ...

The dropdown list in the edit form of jQgrid is displaying an additional quotation mark

In my MVC2 EditStatesController, I have the following code: public JsonResult GetStates() { string statesToReturn = GetStates(); // returns "1: Alabama; 2: Alaska; 3: Arizona; 4: Arkansas" return Json(statesToReturn); } ...

typescript tips for incorporating nested types in inheritance

I currently have a specific data structure. type Deposit { num1: number; num2: number; } type Nice { num: number; deposit: Deposit; } As of now, I am using the Nice type, but I wish to enhance it by adding more fields to its deposit. Ultima ...

What is the method to retrieve content from a different domain using .load()?

When I try to retrieve data from a different domain using .load() or other jQuery ajax functions, it doesn't seem to work. However, accessing URLs on my own domain works perfectly fine. I've heard about a workaround involving PHP and setting up ...

Having trouble getting Javascript to reveal hidden elements based on their class

I am having some trouble making specific fields in a form appear based on the selection made from a dropdown menu. Below is a simplified snippet of my code, which should change the display from 'none' to 'block'. Can you help me figure ...

Acquire the content of a nested element using jQuery

I have a navigation list with separate headlines and text for each item. The goal is to switch the main headline and paragraph of text when hovering over a navigation item. CodePen Example Currently, my code displays all text. I only want to display the ...

What is the best way to clean HTML in a React application?

I am trying to showcase HTML content on the React front end. Here is the input I have: <p>Hello/<p> Aadafsf <h1>H1 in hello</h1> This content was written using CKEditor from the Admin side. This is how it appears on the React fro ...

How do I access the variable value from inside a function in jQuery?

Is it possible to extract the value from 'a = entry.username' outside of the function? I need to retrieve a value that is already being looped inside the function. $('#btnlogin').click(function(){ var usernamelogin = $(&apos ...

Show the flex items arranged horizontally

This template is generated dynamically by Django: <div class="center row"> <h3><span>The Core</span></h3> {% for member in core %} <a class="core_img " href="#"> <div class="img__overlay"> ...

Fade images using jQuery when hovered over

Is there a way to create an interactive image that cycles through multiple images when hovered over, and returns to the original image when the mouse moves away? I'm aiming for a smooth fade effect between images, like transitioning between 3 or 4 dif ...

"Implementing a column template in jqgrid post-creation: A step-by-step

Can't apply column template with Free jqgrid once it's been created. I've attempted: var newOrderPriceTemplate = { align: "center", formatter: "showlink", formatoptions: { onClick: function() { alert('clicked&apos ...

The cookie is mysteriously missing from the request headers after the deployment to Vercel

I have encountered a problem while building my MERN blog app. Everything was running smoothly before deploying to Vercel. The server was hosted on http://localhost:3000 and the client React part was hosted on http://localhost:8000. After deploying, the ser ...

Is there a way to find the JavaScript Window ID for my current window in order to utilize it with the select_window() function in

I'm currently attempting to choose a recently opened window while utilizing Selenium, and the select_window() method necessitates its WindowID. Although I have explored using the window's title as recommended by other sources, and enabled Seleni ...

Deciphering a JSON reply with the Unmarshal function

Currently, I am attempting to parse a JSON response using the code provided below: type Token struct { access_token string `json:access_token` token_type string `json:token_type` expires_in int `json:expires_in` } homeURL := "https:/blah.com/ ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

Converting C# data into XML format

I am currently working with data obtained from the web, which is structured as follows (in a stream): {"parts":[ {"title":"Heading1","logo":"http:\/\/asd.com\/3.png","date":{"d":"24","m":"01","y":"2012"}, "blocks":[ [ {"time":"01:23 ...

Error encountered with NodeJS Express Module: TypeError - Unable to access property 'finished' as it is undefined

Recently, I've been working on creating an API that can extract text from a website based on specific keywords. To achieve this, I utilized Selenium to load the site and retrieve the text. However, I encountered an issue with sending the extracted tex ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

The "offset" parameter has exceeded the acceptable range. It should fall within the range of 0 to 17825792

A critical error has occurred due to an unhandledRejection. It seems that a Promise rejection was not caught: RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of bounds. It should be >= 0 && <= 17825792. Current value is 17825796 at ...