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

Building Cross-Platform Apps With React Native Using JSON API Communication With Express

I'm working on developing a React Native application that utilizes an Express server and PostgreSQL database. Here is the fetch request I have in one of my components: componentDidMount() { fetch('/users') .then(response => respo ...

How can I link two separate webpages upon submitting a form with a single click?

Here is a snippet of my code: <form action="register.php" method="post"> <input type="text" name="uname"> <input type="submit" > </form> Within the register.php file, there are codes for connecting to a database. I am looking ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

Using Vue to input an array

I'm struggling with how to handle this issue. The task involves taking input which should be a URL, and the user should be able to enter multiple URLs. For instance: <input type="text" v-model="fields.urls" class=&quo ...

AngularJS confirmation directive for deleting items

I am currently utilizing this directive for a confirmation prompt when deleting an app. However, regardless of whether I click cancel or yes, the app still gets deleted. <small class="btn" ng-click="delete_app(app.app_id)" ng-show="app.app_id" ng-con ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

When utilizing Md-select in Protractor, how can the dropdown list be accessed?

I am having trouble locating the option from the dropdown menu that I need to select. Despite trying various methods, I have not been successful. <md-select ng-model="card.type" name="type" aria-label="Select card type" ng-change="$ctrl.onCardSelecti ...

arrange a collection within an array containing keys as strings

I am facing an issue with sorting an array of objects. I need to sort the 'list' by 'score' in descending order. var list =[{ '440684023463804938': { score: 6, bonuscount: 2 }, '533932209300832266': { score: 20, b ...

The toggleCategories function seems to be malfunctioning as it is only showing the sequence number as 0 in ReactJS

I am currently working on a portfolio using the React framework. One of the features I have implemented is a project page where multiple projects are displayed within tabs. However, I am facing some issues with the functionality. toggleCategories(){ ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

What is the process for closing the lightbox?

My code is supposed to display a lightbox as soon as the page loads, similar to a popup window. However, there seems to be an issue with closing the lightbox when clicking on the 'x' button at the corner of the box. Unfortunately, the current cod ...

Utilizing Redux state data in a hyperlink: A step-by-step guide

I am a beginner in Redux and ReactJS. I'm working on using a state data called type within the link retrieved via Axios on line 17. The value of type is set from another .jsx file using dispatch(). In this Home.jsx file, dispatch is called on line 24 ...

Utilize multiple conditions to refine data filtering in DynamoDB

Is it possible to apply multiple filters when querying data in Amazon DynamoDB? I need to filter a table based on the post date and district using the scan method. var params = { TableName: table, KeyConditionExpression : 'post_date = :today_ ...

Where is the destination of the response in a Client-Side API Call?

I have developed an API that accepts a person's name and provides information about them in return. To simplify the usage of my API for third parties on their websites, I have decided to create a JavaScript widget that can be embedded using a script ...

When the browser is closed, Express and Redis sessions are unable to persist

Despite setting the maxAge and ttl values in RedisStore for persistent sessions, my session gets destroyed whenever I close the browser. I'm unsure of what mistake I might be making. Any insights on why the session doesn't survive a browser resta ...

Node.js HTTP API for Java applications

In the process of developing a highly scalable backend system from scratch, I have embarked on creating a Node.js Java backend architecture. The middleware in Node.js is responsible for handling HTTP requests sent from an Android application and forwarding ...

Adding a background image to a box in MUI is a simple task that can enhance

I've been attempting to include a background image in the Box component of mui, but I can't seem to get it to work. Here is the code I've been using: const Main = () => { return ( <Box sx={{backgroundImage:'images/cove ...

Struggling to verify credentials on CouchDB

I'm currently facing an issue with authentication while trying to access a couch server from a web application served on port 80. The credentials seem to be removed when passing them in the URL and the session cookie isn't sent to the server. He ...

"Failure encountered while trying to fetch JSON with an AJAX request

I am facing an issue with an ajax request. When I make the request with the property dataType: 'json', I get a parsererror in response. My PHP function returns the data using json_encode(), can someone assist me? On the other hand, when I make th ...

Execute identical task using a for loop in JavaScript

Here is a sample code snippet: var seats = [] for (a = 0; a <= seatsNumFront; a++) { seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515")) } for (b = 0; b <= seatsNumFront; b++) { seats.push(new Se ...