1

i have an array of object ids which i extracted from another instance. these object ids represent user ids in user model. i would like to use these object ids to get the user details

How i got object ids

        const chatrooms = await ChatRoom.find({owners:{$all:[user._id]}}) 
        const allowners = chatrooms.flatMap(room => room.owners) 
        const vendors = allowners.filter(item => !item.equals(userid))

object ids

 vendors = [
           "5d6caee9bb6f2921f45caf1b",
           "5d6dfcd6e3b11807944348b8",.....
           ]

user schema

const userSchema = new mongoose.Schema({
name:{
    type: String,
    require: true,
    trim:true
})

const User = mongoose.model('User', userSchema)

i have tried a for loop which is not working

   const vendorDetails = []
    for(let i=0; i<=vendors.length; i++)
        {
            vendorDetails[i] = User.find({_id:vendors[i]}) 
        }
        console.log(vendorDetails)

Result i am expecting is something like this

   vendorDetails = [ { _id: 5d6caee9bb6f2921f45caf1b,
                    name: 'vithu'
                    },
                    {
                      _id: 5d6dfcd6e3b11807944348b8,
                    name: 'vcs'
                    }....]
3
  • 1
    Possible duplicate of mongodb/mongoose findMany - find all documents with IDs listed in array Commented Sep 7, 2019 at 6:47
  • i tried const vendorDetails = [] vendorDetails = User.find( { _id : { $in : vendors } } ) res.send(vendorDetails) result: {} Commented Sep 7, 2019 at 6:56
  • You need to use the actual code of the duplicate question. Commented Sep 7, 2019 at 7:04

2 Answers 2

4

try this

  db.collection.find( { _id : { $in : yourArrayOfIds } } );
Sign up to request clarification or add additional context in comments.

16 Comments

i tried this: const vendors = allowners.filter(item => !item.equals(userid)); const vendorDetails = []; vendorDetails = User.find( { _id : { $in : vendors } } ) ; res.send(vendorDetails); result:{}
add await in query vendorDetails = await User.find( { _id : { $in : vendors } } ) ;
you need to await this and don't forget to upvote if it works for you ;) @vithushaji
still getting {} @AmirTahani vendorDetails = await User.find( { _id : { $in : vendors } } )
can you check if there is an actual record with this Id ? @vithushaji
|
0

In an attempt to reason about your code, see below example. I hope this helps

async function getVendorDetails(ChatRoomModel, userObject = {}) {
    /* 
         Do your arguments verifications first (not included), then Await the result from User.find() 
         NOTE: I added "async" in front of the function in order to use "await"
         and injected the model into this function to keep it "pure", 
         you can implement this in other ways. Also pass a userObject containing
         your, well, user object :-)
    */
    const chatrooms = await ChatRoomModel.find({ owners: { $all: [userObject._id] } }); // chatrooms is expect to be an Array

    /* 
        Extract allOwners and vendor from the result {chatrooms}
        Note: I modified the variable name allowners -> allOwners
    */
    const allOwners = chatrooms.flatMap(room => room.owners); // allOwners is expected to be an Array

    /* 
        Changed the .equals() to a comparison operator
        Note: I modified the variable name in the filter function callback arg from item -> owner
    */
    const vendors = allOwners.filter(owner => owner !== userObject._id); // vendors is expected to be an Array

    try {
        // Await the result from User.find()
        const result = await User.find({
            _id: {
                $in: vendors
            }
        });
        // Return the result as a resolved promise
        return result;

    } catch (error) {
        // return error as a rejected promise
        return error;
    }
}

// Using the function

const ChatRoom = require('/path/to/model');

const user = {
    _id: '5d6caee9bb6f2921f45caf1b'
};


// Call the function (It returns a promise)

getVendorDetails(ChatRoom, user).then(result => {
    console.log(result);
}).catch((error) => {
    console.log(error);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.