apinot
apinot

Reputation: 85

Find with array of IDs in mongoose

I make an API with Express.js and mongoose. I need to find users whose id is contained in an array.

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

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

All IDs in this array exist.

Then I do :

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

        console.log('followedUser', followedUser);
        // return []
});

followedUser should have two users objects with the matching ids.

How can I resolve this?

Thanks

PS: There is my User model

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);

Upvotes: 7

Views: 15009

Answers (2)

Eugene Obrezkov
Eugene Obrezkov

Reputation: 2996

You can use an $in operator and provide an array of IDs as is to the mongo. E.g. you can query the users that has specified IDs from the array:

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

But, make sure that your followedIDs is an array of ObjectId. MongoDB stores _id as an ObjectId, not the 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 generate such an array from the array of strings, use map:

const followedIDs = yourArrayWithIDAsString.map(ObjectId);

Upvotes: 12

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4915

.in method like

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

Upvotes: 5

Related Questions