【问题标题】:populate field in a subschema document在子模式文档中填充字段
【发布时间】:2019-06-10 22:33:22
【问题描述】:

我有一个数组形式的嵌套子模式,在这个子模式数组中,我引用了 Image 类型的对象 ID(参见图像模式)。 我想要的是用图像本身的数据填充这个对象 ID。 恢复想要填充子模式文档中的字段。 我尝试了很多解决方案,但没有成功,知道如何实现吗? 谢谢

我有 3 个架构,如下所示:

const deviceSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true,
    },
    os: {
        type: String,
        required: true,
    },
   },
    images:[assignedImagesSchema]
});

const  assignedImagesSchema = new mongoose.Schema({ 
    id: {type: mongoose.Schema.Types.ObjectId, ref:"Image"},
    isVisible: {
        type: Boolean,
        default: true
    },
    visibleFor: {
        type: Number,
        default: 0
    },
    orderIndex: {
        type: Number,
    }
  });
const imageSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    url:{
        type: String,
        required: true,

    },
    orientation: {
        type: String,
        required: true,
    },
    devices: [{type: mongoose.Schema.Types.ObjectId, ref:'Device' }]

【问题讨论】:

    标签: mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您可以在 assignedImageSchema 中添加一个将 imageSchema 作为对象的新字段。例如:

    const assignedImagesSchema = 
    new mongoose.Schema({ 
    image: { type: imageSchema } , 
    isVisible: { type: Boolean, default: true },
    visibleFor: { type: Number, default: 0 },
    orderIndex: { type: Number, } });
    
    

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2022-01-18
      • 2020-11-21
      • 2018-08-16
      • 2017-03-14
      • 2021-07-26
      • 1970-01-01
      • 2021-05-20
      • 2014-08-16
      相关资源
      最近更新 更多