Search code examples
node.jsmongoosemongoose-populate

trying to populate each owner of each chatrooms


Each chatroom consist of two owners, one user itself and other party. i am trying to extract the username of other party so that i can send it along with chatroom id

i have tried to populate the owners and so that i can extract the other party details . populate is not working

  const chatRoomSchema = new mongoose.Schema({ 
   owners:[{
        type:mongoose.Schema.Types.ObjectId,
        required:true,
        ref:'User'
   }]

   },{
      timestamps:true  
       })

    //virtuals to relate chatroom with messages
       chatRoomSchema.virtual('chatter', {
             ref:'message',
               localField : '_id',
              foreignField:'room'
             })

        chatRoomSchema.set('toObject', { virtuals: true });
         chatRoomSchema.set('toJSON', { virtuals: true });

       const ChatRoom = mongoose.model('chatroom',chatRoomSchema)

//route for getting details of other party in chat rooms

        router.get('/chatrooms',auth, async (req, res) => {

       const user = req.user

     try {

    //Getting all chatrooms
    const chatroom = await ChatRoom.find({owners:{$all:[user._id]}})


    const chatrooms = await chatroom.populate('owners').execPopulate()
    res.send(chatrooms) 

    } catch (error) {
    res.status(500).send(error)
 }

 })

    const chatroom = await ChatRoom.find({owners:{$all:[user._id]}})

gives following result

    [
       {
       owners: [
          "5d6caefdbb6f2921f45caf1d",
          "5d6caee9bb6f2921f45caf1b"
         ],
        _id: "5d6ccf5d55b38522a042dbb2",
          createdAt: "2019-09-02T08:14:21.734Z",
         updatedAt: "2019-09-02T08:14:21.734Z",
        __v: 0,
       id: "5d6ccf5d55b38522a042dbb2"
        },
       {
           owners: [
       "5d6dfcd6e3b11807944348b8",
       "5d6caefdbb6f2921f45caf1d"
                      ],
      _id: "5d6dfd48e3b11807944348ba",
          createdAt: "2019-09-03T05:42:32.572Z",
          updatedAt: "2019-09-03T05:42:32.572Z",
         __v: 0,
      id: "5d6dfd48e3b11807944348ba"
      }
      ]

but populate gives {}


Solution

  • What i was trying to do is to extract the other party in each chat room and send them back to client. Following steps were taken

    1) populate owners of the chat room

      const chatrooms = await ChatRoom.find({owners:{$all:[user._id]}}).populate('owners','-password').exec()
    

    2) Extract all owners to one array

      const allowners = chatrooms.flatMap(room => room.owners) 
    

    3) Extract all owners other than user in each chatroom

      //declared userid = user._id
      const vendors = allowners.filter(item => !item.equals(userid))