Search code examples
node.jsmongodbmongoosemongoose-schema

Retrieve information from reference ObjectId MongoDB


I have this scheme

const friendSchema = new mongoose.Schema(
  {
    friend_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Users",
  },
     status: String,
  },
  { _id: 0 } 
);

and this model is using it

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  password: {
    type: String,
  },
  rate: {
    type: Number,
    default: 0,
  },
  friend: [friendSchema],
})

just like a user having friends and i wanted to get every user and their friends (name - rate)

status in the friendSchema is the status of friend request (accepted - pending) i am using this code

let users = await User.find().select('-password').populate({ path: 'friend.$.friend_id' ,  select: 'name rate' })

when i tried with postman using this route i get every user and the status of friends only without the name - rate of every friend

how can i get every user and the information of their friends ?


Solution

  • Try without .$, like this:

    let users = await User.find().select('-password').populate({ path: 'friend.friend_id',  select: 'name rate' })