使用Mongoose填充嵌套数组

问题描述 投票:0回答:2

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

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'以便我可以填充它们?

node.js mongodb mongoose mongoose-populate
2个回答
1
投票

事实证明它就是这么简单

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

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' }]
});`

获得赎回卡的逻辑: -

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文件。希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.