使用Mongoose填充嵌套数组

时间:2017-12-26 19:00:54

标签: node.js mongodb mongoose mongoose-populate

我有一个如下所示的用户架构,我试图填充实时项目数组,但我无法弄清楚如何访问它。

const userSchema = new Schema({
  local: {
    email: String,
    username: String,
    password: String,
    liveProjects: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'liveProject'
    }]
  },
  google: {
    googleId: String,
    email: String,
    username: String,
    liveProjects: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'liveProject'
    }]
  }
});

const User = mongoose.model('user', userSchema);
module.exports = User;

如果没有嵌入我可以使用

User.findById(id).populate('liveProjects').exec((err,projects)=>{});

但是如何访问'local.liveProjects''google.liveProjects'以便我可以填充它们?

2 个答案:

答案 0 :(得分:1)

事实证明它就像

一样简单
User.findById(id).populate('local.liveProjects').exec((err,projects)=>{});

答案 1 :(得分:0)

用户架构

 `let UserSchema = new Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    profile: {
        firstName: {type: String,required: true},
        lastName: {type: String,required: true},
        address1: {type: String},
        address2: {type: String},
        city: {type: String},
        state: {type: String},
        zip: {type: String},
        phone: {type: String,required: true},
        avatar:{ type: Schema.Types.ObjectId, ref: 'Avatar'},
        shippingAddress:{
            address1: {type: String},
            address2: {type: String},
            city: {type: String},
            state: {type: String},
            zip: {type: String}
        },
    },
    redemptionCards : [{ type: Schema.Types.ObjectId, ref: 'CardCodes' }]
});`

获得RedemptionCards的逻辑: -

User.findOne({ email }).populate("redemptionCards")
            .exec(function (err, user) {
                CardData.populate(user.redemptionCards, {path: 'redemptionCards',match: { _id: { $ne: null }}}, function (err, cards) {
    console.log(cards);
});

仅供参考 - CardData是硬编码的JSON文件。希望这会有所帮助。