无限人口猫鼬节点js

时间:2020-07-20 12:21:21

标签: node.js database mongodb mongoose

我有两个模型((表单,用户)

每个用户都有formId字段,这是他拥有的表单对象的对象ID

每个表单都有一个名为userId的字段,适用于拥有此表单的用户

问题是我使用的是mongoose-autopopulate软件包,如果我将formId和userId字段更改为自动填充,它将打开无穷无尽的人口

问题是其他一些模式有一个名为formId的字段,该字段与表单对象相关联,在这种情况下,我想填充userId字段以获取用户信息,而无需再次填充formId字段。

模式设计


const userSchema = new Schema({
  name: String,
  age: Number,
  formId: {
    type: Schema.Types.ObjectId,
    ref: 'Form',
    
    //this value used to auto populate for mongoose-autopopulate package
    autopopulate: true,
  },
})

//signing the mongoose-autopopulate plugin

...

//exporting the module




---------------



const formSchema = new Schema({
  address: String,
  bill: Number,
  //the id of the user who added this form
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    
    //this value used to auto populate for mongoose-autopopulate package
    autopopulate: true,
  },
})

//signing the mongoose-autopopulate plugin

...

//exporting the module




----------


const orderSchema = new Schema({
  products: [],
  deliveryBoy: {
    type: Schema.Types.ObjectId,
    ref: 'Boy',
  },
  formId: {
    type: Schema.Types.ObjectId,
    ref: 'Form',
    
    //this value used to auto populate for mongoose-autopopulate package
    autopopulate: true,
  },
})

//signing the mongoose-autopopulate plugin

...

//exporting the module

谢谢

1 个答案:

答案 0 :(得分:0)

使用 maxDepth 选项 mongoose-autopopulate

例如

const orderSchema = new Schema({
  products: [],
  deliveryBoy: {
    type: Schema.Types.ObjectId,
    ref: 'Boy',
  },
  formId: {
    type: Schema.Types.ObjectId,
    ref: 'Form',
    autopopulate: { maxDepth: 2 },
  },
})