【问题标题】:Populate nested array with Mongoose使用 Mongoose 填充嵌套数组
【发布时间】:2018-06-07 12:51:32
【问题描述】:

我有一个如下所示的用户架构,我正在尝试填充实时项目数组,但我不知道如何访问它。

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


    【解决方案1】:

    此处为用户架构

     `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 文件。希望这会有所帮助。

    【讨论】:

    • redemptionCards 未在架构中列出?
    • 是的。给你: redemptionCards : [{ type: Schema.Types.ObjectId, ref: 'CardCodes' }],
    • 也许我错过了什么。在您发布的架构中 redemptionCards 不显示为主要对象或子对象。
    • 谢谢,这更有意义。现在,如果您的 redemptionCards 数组包含在您的配置文件对象中,您将如何填充它?这是我的问题
    • 我还添加了代码逻辑,以便在上方填充兑换卡。
    【解决方案2】:

    原来是这么简单

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

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2020-06-07
      • 2019-12-06
      • 2016-10-12
      • 2019-09-23
      • 2017-01-01
      • 2014-10-27
      • 1970-01-01
      相关资源
      最近更新 更多