0

I'm having some trouble with the populate function in Mongoose. The problem is that the contactpersons does not get sorted, so I get all of them, regardless of the club I'm using.

models.js

// Contactperson Schema
var contactPersonSchema = new Schema({
    club: {
        type: Schema.ObjectId,
        ref: 'Club'
    },
    name: String,
    phoneNumber: String,
    email: String,
    position: String,
    comment: String
});


// Club Schema
var clubSchema = new Schema({
    name: String,
    postalPlace: String,
    comment: String,
    status: String
});

routes.js

router.use('/api/clubs', clubRoute);

clubroutes.js

router.route('/:club_id/contactpersons')
    .post(function (req, res) {
        var contactperson = new Contactperson();
        contactperson.club = req.body.club;
        contactperson.name = req.body.name;
        contactperson.phoneNumber = req.body.phoneNumber;
        contactperson.email = req.body.email;
        contactperson.position = req.body.position;
        contactperson.comment = req.body.comment;

        contactperson.save(function (err) {
            if (err) {
                res.send(err);
            }

            res.json({message: 'Contactperson created!'});
        });
    })
    .get(function (req, res) {
        console.log(req);
        Contactperson.find({}).populate('club').exec(function (err, contactpersons) {

                if (err) {
                    res.send(err);
                }

                res.json(contactpersons);
            });

    });

clubDetail.js in Angular (I'm using Restangular)

$scope.club = clubService.one($routeParams.id).get().$object;

$scope.contactpersons = clubService.one($routeParams.id).all('contactpersons').getList().$object;
halfer
  • 19,824
  • 17
  • 99
  • 186
Martin Brandhaug
  • 1,052
  • 1
  • 10
  • 21

1 Answers1

0

I finally found out the answer. The problem was that i did not define the club. Here is the correct find method:

Contactperson.find({club:req.params.club_id}).populate('club').exec(function (err, contactpersons) {

Martin Brandhaug
  • 1,052
  • 1
  • 10
  • 21
  • Glad you got it working, but what does that change have to do with getting population to work? Wouldn't that just filter the returned docs to just those with the matching `club`? – JohnnyHK Aug 19 '16 at 16:49
  • Yes, that was what I was trying to accomplish. Isn't that what you would use populate for? – Martin Brandhaug Aug 23 '16 at 08:09
  • No, [population](http://mongoosejs.com/docs/populate.html) is used to follow up your original Contactperson query with a second one to the referenced (Club) model to pull in the referenced club document instead, replacing the `club` ObjectId in the contactperson with the doc. – JohnnyHK Aug 23 '16 at 12:15