-1

I am trying to query out multiple user profiles and then populate each one of the profiles and send it to the client side of my web application. But it's failing miserably. I have done my research and tried everything but it still won't populate it. Here's my axios request to my backend :

router.get("/all", (req, res) => {
errors = {}

Profile.find().populate('user', ['name', 'avatar'])
    .then(profiles => {
        if (!profiles) {
            errors.noprofile = " there are no profiles"
            res.status(404).json(errors)
        }
        else {
            res.json(profiles)
        }
    }).catch(err => res.json(errors))

})

Here user property of the profile isn't populating and i am getting just a user id in my profile collection. I have used findOne({user:req.user.id}) to fetch a particular user and then populate it using populate('user',['name','avatar']) above in my file and it has worked absolutely fine.

halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

1

Following code may be work, in path option it should be your field name which is available in your profile schema and in model option the name of model which is reference model schema

router.get("/all", (req, res) => {
        errors = {}

        Profile.find({})
            .populate({
                path: 'user',
                model: 'user',
                select: 'name avatar',
            })
            .exec(function (err, profiles) {
                if (err) {
                    errors.noprofile = " there are no profiles"
                    res.status(404).json(errors)
                } else {
                    res.json(profiles)
                }
            });
})
laxman
  • 1,338
  • 2
  • 10
  • 27
0

.populate() needs a query to attach itself to, try .find({})

A.Abdelhak
  • 140
  • 4