在使用populate()的某些情况下,mongoose虚拟属性不会填充

时间:2014-07-14 08:05:34

标签: node.js mongodb mongoose mongoose-populate

我正在尝试填充job.creator并使用User对象(user.profile)中的虚拟属性来仅为作业创建者提供公开信息。

/**
 * 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 },
});

当我尝试从.profile对象获取虚拟属性job.creator时,我遗漏了一些值:

//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
        }
    }
}

它也缺少job.creator.profileImageUrls,这是User对象的虚拟属性。

2 个答案:

答案 0 :(得分:0)

我建议不要使用job.creator = job.creator.profile行,这与Mongoose的工作原理并不相符。此外,profileImageUrls来自哪里?似乎不在架构中。

答案 1 :(得分:0)

我不知道这是否可取,但我得到了以下内容:

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

res.json(jobs);