【问题标题】:How to populate object having array of object in mongoose?如何在猫鼬中填充具有对象数组的对象?
【发布时间】:2020-10-13 07:16:51
【问题描述】:

我想将adminId 路径填充到User 模型。
这是代码

adminInfo: {
    _id: false,
    adminId: [{
      type: Schema.Types.ObjectId,
      ref: 'User'
    }]
 }

这是用户架构的一部分:

// user schema
const UserSchema = new mongoose.Schema({
  name: {
    firstName: {
      type: String,
      trim: true,
      required: true,
    },
    lastName: {
      type: String,
      trim: true
    }
  },
  email: {
    type: String,
    trim: true,
    required: true,
    unique: true,
    lowercase: true
  },
  phone: {
    type: String,
    trim: true,
    minlength: 10,
  },
  password: {
    type: String,
    trim: true,
    required: true,
    minlength: 6
  }
});

我尝试过使用 .populate('adminInfo.adminId'),但它给出的是空数组 [] 而 .populate('adminInfo') 给出了管理员 ID 的数组,但没有填充到用户模型中

【问题讨论】:

  • 嗨!请将用户架构添加到问题中
  • 嗨 @Tunmee 更新了!
  • 我认为adminInfo 属性是用户模式的一部分,从您的最新编辑来看,我可以看到它不是。您还可以分享adminInfo 属性所在的架构吗
  • @Tunmee 如果adminInfo 属性将成为用户模式的一部分,那么我为什么要引用该用户模式? adminInfo 属性是 admin 架构的一部分,我想将 adminId 填充到用户架构
  • 你也可以分享admin架构

标签: node.js mongodb web mongoose


【解决方案1】:

我认为.populate('adminInfo.adminId') 方法没有任何问题。

您确定 ref 字段在 CamelCase 中吗?

如果没有,请尝试更改 ref 字段 ->

adminInfo: {
  _id: false,
  adminId: [{
    type: Schema.Types.ObjectId,
    ref: 'user'
  }]
}

【讨论】:

  • 是的,我敢肯定,当我将 schena 更改为:adminId:[ { type: Schema.Types.ObjectId, ref: 'User' }] 然后.populate('adminId') 时,它也可以工作
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 2021-08-16
  • 2014-11-25
  • 1970-01-01
  • 2019-11-27
  • 2017-04-29
  • 2014-07-24
相关资源
最近更新 更多