0

I'm trying to populate the job.creator and use the virtual attribute from the User object (user.profile) to give only public information for the job creator.

/**
 * User Schema
 */
var UserSchema = new Schema({
    favorites: {
        jobs: [{ type: Schema.ObjectId, ref: 'Job', index: true }]
    }
});

// Public profile information
UserSchema
.virtual('profile')
.get(function () {
    return {
        favorites: this.favorites,
        profileImageUrls: this.profileImageUrls //also not being populated
    };
});


UserSchema
.virtual('profileImageUrls')
.get(function(){
    var  defaultUrl = cfg.home + '/images/cache/default-profile-img.png'
        , smallUrl = cfg.home + '/images/cache/default-profile-img-small.png';

    return {
        small: smallUrl
        , default: defaultUrl
    };
});


/**
 * Job Schema
 */
var JobSchema = new Schema({
    creator: { type: Schema.ObjectId, ref: 'User', index: true, required: true },
});

When I try to get the virtual attribute .profile from the job.creator object, I am missing some values:

//controller
Job.populate(job, { path: 'creator', select: '-salt -hashedPassword' }, function(err, job){
    if ( job.creator ) {
        job.creator = job.creator.profile; //this is missing some attributes
    }

    return res.json(job);
})


{
    //...
    creator: {
        favorites: {
            jobs: [ ] //this is not being populated
        }
    }
}

Its also missing job.creator.profileImageUrls which is a virtual attribute off the User object.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
chovy
  • 72,281
  • 52
  • 227
  • 295

2 Answers2

0

I'd recommend not doing the job.creator = job.creator.profile line, that doesn't really jibe well with how Mongoose works. Also, where is profileImageUrls coming from? Doesn't seem to be in the schema.

vkarpov15
  • 3,614
  • 24
  • 21
  • can you look at my posted answer? I got it working, but I don't know what the impact is of doing `job._doc.creator = job.creator.profile` – chovy Jul 15 '14 at 03:14
0

I don't know if this is desirable, but I got it working with the following:

_.each(jobs, function(job, i){
    if ( job.creator ) {
        job._doc.creator = job.creator.profile;
    }
});

res.json(jobs);
chovy
  • 72,281
  • 52
  • 227
  • 295