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'
                    }....]
vithu shaji
  • 339
  • 3
  • 14
  • 1
    Possible duplicate of [mongodb/mongoose findMany - find all documents with IDs listed in array](https://stackoverflow.com/questions/8303900/mongodb-mongoose-findmany-find-all-documents-with-ids-listed-in-array) – str Sep 07 '19 at 06:47
  • i tried const vendorDetails = [] vendorDetails = User.find( { _id : { $in : vendors } } ) res.send(vendorDetails) result: {} – vithu shaji Sep 07 '19 at 06:56
  • You need to use the actual code of the duplicate question. – str Sep 07 '19 at 07:04

2 Answers2

4

try this

  db.collection.find( { _id : { $in : yourArrayOfIds } } );
Amir Tahani
  • 688
  • 5
  • 13
  • 1
    i tried this: const vendors = allowners.filter(item => !item.equals(userid)); const vendorDetails = []; vendorDetails = User.find( { _id : { $in : vendors } } ) ; res.send(vendorDetails); result:{} – vithu shaji Sep 07 '19 at 06:58
  • 1
    add await in query vendorDetails = await User.find( { _id : { $in : vendors } } ) ; – sushant mehta Sep 07 '19 at 07:11
  • 1
    you need to await this and don't forget to upvote if it works for you ;) @vithushaji – Amir Tahani Sep 07 '19 at 07:15
  • 1
    still getting {} @AmirTahani vendorDetails = await User.find( { _id : { $in : vendors } } ) – vithu shaji Sep 07 '19 at 07:16
  • 1
    can you check if there is an actual record with this Id ? @vithushaji – Amir Tahani Sep 07 '19 at 07:17
  • try after converting array of string to array of mongoose object ids const vendors = vendors.map(item => mongoose.Types.ObjectId(item)) – sushant mehta Sep 07 '19 at 07:19
  • const vendors = allowners.filter(item => !item.equals(userid)) console log [ 5d6caee9bb6f2921f45caf1b, 5d6dfcd6e3b11807944348b8 ]; vendors = vendors.map(item => mongoose.Types.ObjectId(item)) nothing in console after this – vithu shaji Sep 07 '19 at 08:38
  • @AmirTahani i checked the record "_id" : ObjectId("5d6dfcd6e3b11807944348b8") "_id" : ObjectId("5d6caefdbb6f2921f45caf1d"), they exisit – vithu shaji Sep 07 '19 at 08:46
  • @vithushaji try adding ObjectId to your array – Amir Tahani Sep 07 '19 at 08:58
  • @AmirTahani console.log(user._id) gives this result for current user . 5d6caefdbb6f2921f45caf1d ; i think adding objectid may not solve the issue – vithu shaji Sep 07 '19 at 09:04
  • @vithushaji it's acting weird I wish I had access to see issue myself – Amir Tahani Sep 07 '19 at 09:14
  • @AmirTahani https://drive.google.com/open?id=1dnFNEGTLIri5F0wVucFAFnBZlpTJDO26 src folder you can check routers/chat – vithu shaji Sep 07 '19 at 09:43
  • @vithushaji you can handle it all in 1 query ChatRoom.find({owners: {$all: [user_d]}, $neq: owner.id}).populate(); something like this – Amir Tahani Sep 07 '19 at 09:49
  • what i am trying to do is finding out all chat rooms with current user and then extract the detials of other owner. $neq: owner.id i couldnt get – vithu shaji Sep 07 '19 at 10:07
  • 1
    @AmirTahani const chatrooms = await ChatRoom.find({owners:{$all:[user._id]}}).populate('owners','-password').exec() worked – vithu shaji Sep 07 '19 at 15:18
  • 1
    You are fantastic Amir :D – Pedram marandi Sep 16 '19 at 06:42
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);
});
Grey
  • 489
  • 3
  • 7