Mongodb: Search for IDs within a nested array field

My MongoDB data structure includes user profiles with friend request information. Here's an example:

{
    _id: "someId",
    profile: {
        username: "oliv",
        friendRequests: [
            { fromUserId: "anId", accepted: false, created: "someDate"},
            { fromUserId: "otherId", accepted: true, created: "otherDate"}
        ]
}

I'm trying to retrieve the user objects referenced in my logged-in user's friend requests. I attempted this query:

Meteor.users.find({_id: {$in: Meteor.user().profile.friendRequests.fromUserId}});
// Note: Meteor.users is the collection and Meteor.user() gets the current user

Unfortunately, it's not working, possibly due to the nested array structure.
Is there a way to instruct MongoDB to iterate through the fromUserId values?

Thank you

Answer №1

Modify your query to:

Meteor.users.find({_id: {$in: _.pluck(Meteor.user().profile.friendRequests, 'fromUserId') }});

Explanation:

friendRequests contains an array of objects, and $in requires an array of strings (the ids). By utilizing _.pluck, you can extract the values of fromUserId from each object in the array.

Answer to query ("what if I only want to retrieve the ids from friend requests where "accepted" is false?"):

_.pluck(
    _.filter(Meteor.user().profile.friendRequests, function (req) {
        return !req.accepted;
    }),
    'fromUserid'
);

Visit Underscore filter documentation

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

Error: Attempting to modify a constant value for property 'amount' within object '#<Object>'

After fetching data from an API, I stored an array in a state. Upon trying to update a specific field within an object inside the array using user input, I encountered the error message: 'Uncaught TypeError: Cannot assign to read only property 'a ...

Incorporating a loading animation with an AJAX call

I've come across various solutions to this issue, one of the most enlightening being a response on Stack Overflow suggesting to "display it as soon as you initiate the AJAX call" and then "hide the image once the request is complete." But how would I ...

Using Typescript does not generate any errors when indexing an object with brackets

One interesting thing I've noticed about TypeScript is that it allows me to use bracket notation to access an object via index, even when it only has keys. For example: interface testObject { name: string; id: number; } let first: testObject ...

What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6. My goal is to leverage ES2019 features in my own code. Ultimately, I aim to output ES6. This is how I set up my tsconfig { "compilerOptions": { "module": "CommonJS" ...

Sending the slider value from a website to a program when the slider is adjusted

I have been experimenting with programming an ESP32 to regulate the LED brightness using a slider. I've pieced together some information from tutorials found on and Currently, I've achieved the ESP32 connecting to my network, displaying the sli ...

Discovering common elements in two multi-dimensional numpy arrays

I recently started learning Python and I've encountered an issue. import numpy as np def find_neighbors(indexset, i,j): temp = np.array([[i-1,j],[i+1,j],[i,j-1],[i,j+1]]) for ele in temp: if ele in indexset: print(ele) ...

Three.js - Exploring the Significance of "THREE" within the THREE.scene Framework

Just starting out in JavaScript and experimenting with animations using three.js library. I'm trying to grasp the meaning behind: const scene = new THREE.Scene(); Why is the "THREE" necessary in THREE.Scene? Could we not simply write const scene = n ...

What steps can be taken to empower users to make changes to pre-selected data within the vue-select component?

Usage of vue-select component: Currently, I am looking for a way to enable my users to edit data that has already been selected. After going through the documentation, I couldn't find a direct method to achieve this. If anyone has experience working ...

Retrieve all articles in groups of 10, ensuring that each article includes the necessary details of relevant users

In my project, I have set up two models named user and article. The data structure for each model is outlined below: const userSchema = Schema({ name: String, email: String, password: String }); const User = mongoose.model(‘user’, userSchema); mo ...

Is it secure to store information that impacts component rendering within a JWT payload?

I am currently developing a MERN app where users have various roles, and different components are rendered based on their role in React. In my application, I store a JWT containing the user's ID and role in a cookie, which is then decoded in a global ...

Issue with large date changes causing MUI DatePicker to freeze

The MUI DatePicker, whether from Labs or X, was functioning perfectly. However, I am now facing an issue where it hangs when trying to change the date by ten years. It appears that the code gets stuck in an endless loop, yet there are no errors displayed i ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

TSLint is encountering the error code TS2459: The module "@azure/core-tracing" claims to have a local declaration of "Span" but does not export it, along with additional errors

I'm completely lost on how to tackle this error. The message I'm getting doesn't provide much insight, other than indicating an issue with the installation of '@azure/ai-text-analytics'. I've gone through the process of uninst ...

What is causing the error in this particular stream function?

I created a function that logs the provided arguments to the console when piped into it. function logToConsole() { var stream = new Stream.Transform({objectMode: true}), args = [].slice.call(arguments); stream._transform = function (data, ...

What is the best way to automatically create a list of file names that can be used in a Grunt task?

I am currently utilizing load-grunt-config and grunt-prompt for my project development. I am working on an init task that involves moving php templates between folders. At the moment, I have hardcoded the template filenames, but I would prefer if Grunt co ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

JavaScript for Loading and Moving Ads in IE8

On my website at , I have placed my AdSense ads at the top of the page. However, I encountered an issue with Internet Explorer 8 where the Javascript code I used to move the ads to a different position on the page doesn't seem to work: <!-- POSI ...

What could be causing my string array to not appear in the console when I try to print it?

I am currently using an array called monsterPicker to store names. My goal is for monsterNamer to select a name from the array and transfer it to monsterName. At least, I think that's how it should work. I attempted to move the array into the monster ...

Determine if an object is already present in a JSON array by comparing their respective IDs

I have a shopping cart stored in JSON format. [{"tuote":{"id":"2","name":"Rengas 2","count":16,"price":"120.00"}},{"tuote":{"id":"1","name":"Rengas 6","count":"4","price":"25.00"}},{"tuote":{"id":"4","name":"Rengas 4","count":"4","price":"85.00"}}] Form ...