代码之家  ›  专栏  ›  技术社区  ›  Omar Bahutair

MongoDB中的引用

  •  2
  • Omar Bahutair  · 技术社区  · 1 年前

    我有一个应用程序,其中一个文档想要引用另一个文档,这里的问题是其他文档可能在两个不同的集合中。有没有办法做到这一点,请记住,当它们被提取时,我必须填充它们。

    const schemaOne = new Schema({
       name: string,
    // other fields
    })
    
    const schemaTwo = new Schema({
       name: string
    // other fields
    })
    
    const schemaThree = new Schema({
    // I want to reference a document from schemaOne or two in one field
       someId: ObjectId,
    })
    

    我不想做的解决方案是创建两个字段,一个用于schemaOne,另一个用于chemaTwo。但我认为这会带来更多的复杂性。

    1 回复  |  直到 1 年前
        1
  •  3
  •   jQueeny    1 年前

    您可以使用 refPath 。这允许您在中具有字段 schemaThree 指定当您 populate .

    const schemaThree = new Schema({
       someId: {
          type: Schema.Types.ObjectId,
          refPath: 'modelNameSpecifier', //< this is used during populate()
       },
       modelNameSpecifier: {
          type: String,
          required: true,
          enum: ['ModelOne', 'ModelTwo']
       }
    });
    
    const docs = await ModelThree.find({}).populate('someId');
    

    使用创建文档时 ModelThree 只要确保保存 ObjectId 在中 someId 与之相关的模式的字段 Objectid 在中 modelNameSpecifier 作为任一 ModelOne 对于 schemaOne ModelTwo 对于 schemaTwo .