Searching for an array of IDs in Mongoose

I have created an API using Express.js and mongoose to find users based on their ids in an array.

// Here is the array of user ids
const followedIds = follow.map((f) => f.followed);

console.log(followedIds);
// This will log [ '5ebaf673991fc602045ed47f', '5ebc6fb9af8add09edd842e9' ]

All the IDs in this array are valid and exist.

Next, I execute:

User.where('_id').in(followedIds).exec()
    .then((followedUser) => {

        console.log('followedUser', followedUser);
        // This should ideally return two user objects that match the provided ids
});

The followedUser variable should contain information about the specified users.

Could someone help me understand why my query is not returning the expected results?

Thank you!

PS: Below is my User model definition

const mongoose = require('mongoose');

const user = new mongoose.Schema({
    username: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true },
    avatar: { type: String, default: '/images/avatar_default.jpg' },
    banner: { type: String, default: '/images/banner_default.jpg' },
    created_at: { type: Date, required: true },
    deleted_at: { type: Date, required: false },
}, { versionKey: false });

module.exports = mongoose.model('user', user);

Answer №1

If you need to query users with specific IDs in MongoDB, you can utilize the $in operator. Simply provide an array of IDs to the mongo query like this:

const followedUsers = await User.find({ _id: { $in: followedIDs } });
console.log(followedUsers);

Ensure that your followedIDs is an array of ObjectId, as MongoDB stores _id as an ObjectId data type, not a string.

db.inventory.insertMany([
   { item: "journal", qty: 25, status: "A" },
   { item: "notebook", qty: 50, status: "A" },
   { item: "paper", qty: 100, status: "D" },
   { item: "planner", qty: 75, status: "D" },
   { item: "postcard", qty: 45, status: "A" }
]);

db.inventory.find({ _id: { $in: [ObjectId("your_id_here")] } });

To convert an array of strings into an array of ObjectIds, you can use the map method:

const followedIDs = yourArrayWithIDAsString.map(ObjectId);

Answer №2

.in function example:

User.find().where('_id').in(followedIds)

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

How to Override Certificate Expiry in JavaScript

Is there a way to bypass security for an expired certificate when making an Https post request in Javascript? I have been successful in doing this with C# and Java, but unsure about how to proceed in JavaScript. function post() { var xmlhttp; xmlhtt ...

What could be the reason for the inability to generate the response using response.writeHead and response.write functions?

I recently started learning about node.js and I'm facing an issue with the code inside the if and else loop for the '/socket.html' case. Despite my efforts, I always get a 200 status code and a blank response when accessing the URL localhost ...

Experiencing challenges accessing information from the useEffect hook in React

I'm facing some issues with my useEffect hook and I can't seem to figure out why it's not working. I've been trying to make a call to an endpoint, but it seems like I'm not getting any response back. Any help would be greatly appr ...

Leveraging personalized design elements from a theme in Material UI without the need for makeStyles

Is there a way to access the theme.customElements.actionButton in MyComponent without relying on makeStyles? For instance, can I directly use className={theme.customElements.actionButton}? theme.js const theme = createMuiTheme({ customElements: { ...

Unable to utilize $regex for searching by _id in Mongoose version 6.6.3

My attempt to search data by id is as follows: _id: { $regex: '63a1bda46ec7f02cf5e91825', $options: 'i' }, }) .populate('user', 'name') .sort({ updatedAt: -1 }); Unfortunately, this r ...

Is the existence of the file also verified by JavaScript's realpathSync() function?

I want to utilize node.js FileSystem realpathSync() to find the actual path of a file. Does realpathSync() also verify if the file exists? Would this code be sufficient: try { res = fs.realpathSync(path); } catch (err) { ...

Pass the value of the search input to child components in Angular 2

Within my Angular 2 application, I am faced with the task of sending the value from an HTML search input to 3 child components only when the user pauses typing for 300ms and has entered a different value than what was previously in the input field. After r ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

Passport, Bcryptjs, Async/Await: validate function successfully authenticates any password passed in as input

My passport-local strategy is working perfectly fine, except for one issue with the verifyCallback function. The problem lies in the fact that regardless of the result of the validatesPassword function, it always returns true. This could be due to the fact ...

Loading Animation for Pages and Tables

I'm experiencing a choppy and sudden transition when switching between two pages that contain tables populated using ng-repeat. Upon loading, the footer is positioned halfway up the page below the table heading until the table loads and the layout adj ...

Having trouble getting the Bootstrap tooltip to work on a Select option?

Is there a way to have a tooltip displayed for each option in the select box? <select ng-model="rightList" class="form-control" size="13" multiple> <option ng-repeat="item in selectedList" value="{{$ ...

Tips for automatically updating the time in a React application while utilizing the 'date-fns' library

I've been working on my personal Portfolio using React and I'm looking to add a feature on the landing page that showcases my local time and timezone to potential recruiters. However, there's a small hiccup in my implementation. The displaye ...

Looking for the temporary folder created by the nodejs filesystem?

After encountering path issues with writing values from a textarea to a file using fs, I turned to stackoverflow and discovered that the path should be a tmp folder. Following this advice, the terminal indicated success with the process. However, now I am ...

Adding color between lines in Three.js

I have two different sets of vertices. One set contains real vertices, and the other set contains the same vertices but with a y value of zero. I am trying to connect these vertices and fill them in but have not been successful so far. I have attempted to ...

Exploring the implementation of JavaScript bit-shift and bit-wise operations in Java

I'm currently attempting to emulate the functionality of JavaScript bit-shift and bitwise operations in Java. Have you ever tried to accomplish this task, and how can it be done reliably and consistently even when dealing with long integers? var i ...

Update the form action URL when a specific option is selected from the dropdown menu upon clicking the submit

I would like my form to redirect to a specific page on my website based on the selection made in the <select> tag. For instance, if '2checkout' is selected, it should go to gateways/2checkout/2checkout.php. Similarly, if 'Payza' i ...

Infinite loop triggered by jQuery dropdown menu on page resize was causing an issue

I have been working on developing a navigation menu for a website that displays as a horizontal bar on larger screens, but transforms into a jQuery dropdown menu when the window width is less than 980px. During initial page load with a window width below ...

Ways to utilize $document within a Modal

I'm struggling to utilize the $document in the modals controller. Is there a proper way to pass it in? Just using document is not allowed according to our Angular project guidelines. How I call the modal: var modalInstance = $uibModal.open({ t ...

Avoid mutating the prop directly and instead, utilize a data or computed property that is based on the value of the prop. The prop that is being mutated in this case is

Help me understand this issue that Vue is displaying, I am not sure what is going on. This is my progress element: <el-progress :percentage="percentCompleted" v-show="uploadingVideo"></el-progress> data() { return{ percentCompleted: 0 ...

setTimeout is only effective for durations less than 1000 milliseconds

I am trying to implement a timeout function that displays an alert two seconds after a form is submitted. The code I have tried using does not seem to be working as expected: $(document).ready(function() { $("#newsletter").submit(function() { setTi ...