【问题标题】:mongoose virtual attribute not populating in some cases where populate() is used在某些使用 populate() 的情况下,mongoose 虚拟属性不会填充
【发布时间】:2014-09-04 02:32:19
【问题描述】:

我正在尝试填充 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 },
});

当我尝试从 job.creator 对象中获取虚拟属性 .profile 时,我缺少一些值:

//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,这是用户对象的一个​​虚拟属性。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

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

    【讨论】:

    • 你能看看我发布的答案吗?我得到它的工作,但我不知道这样做有什么影响job._doc.creator = job.creator.profile
    【解决方案2】:

    我不知道这是否可取,但我可以使用以下方法:

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

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 2020-05-18
      • 2016-02-14
      • 1970-01-01
      • 2021-03-15
      • 2020-12-08
      • 1970-01-01
      • 2021-04-26
      相关资源
      最近更新 更多