Abdulaziz.Musaileekh
Abdulaziz.Musaileekh

Reputation: 325

Mongoose populate followers same document

I need to populate ObjectId parameters from the same Schema of users What am trying to do is I have 'Users' document and each record has followers and the ref is the same schema of users.

var userSchema = new Schema({
  username: {type: String, unique: true, trim: true},
  password: {type: String},
  email: {type: String, trim: true},
  avatar: {type: String},
  fullname: {type: String},
  bio: {type: String},
  phone: {type: Number},
  country: {type: String},
  postal: {type: Number},
  followers: [{ type: Schema.ObjectId, ref: 'User' }],
  followed: [{ type: Schema.ObjectId, ref: 'User' }],
  registered: {type: Date, default: Date.now}

});

var User = mongoose.model('users',userSchema);

Now when I tried to print the user information followers array return with ObjectId not the whole information

I try to print with this snippet

User.find().exec(function(error, groups) {    
    return res.status(200).send(groups);
  });

Upvotes: 1

Views: 539

Answers (1)

Kxng Kombian
Kxng Kombian

Reputation: 467

What you want to achieve here is

User.find({})
.populate('followers')
.populate('followed')
.then(users => {

})

This will populate with both the followers and followed with their respective user objects

Upvotes: 1

Related Questions