如何从猫鼬虚拟返回嵌套值

时间:2021-07-18 08:37:18

标签: node.js mongodb mongoose

我有以下猫鼬模式:

const child1 = new mongoose.Schema({
  somearray: [String]
})

const child2 = new mongoose.Schema({
  topSchema: {
    type: mongoose.Schema.Types.ObjectId
    // Id of the topSchema that holds the corresponding child1 instance
  },
  child1Index: {
    type: Number,
    min: 0
    // Index of the entry in child1.somearray
  }
})

child2.virtual('child1String', {
  ref: 'topschema',
  localField: 'topSchema',
  foreignField: '_id',
  justOne: true,
  // and now? => return matched-top-schema.child1[child2.child1Index]
})

const topSchema = new mongoose.Schema({
  child1: [child1],
  child2: [child2]
})

每个 topSchema 实例为 child1 和 child2 存储一个数组。 child1 包含一个数组,其中包含一些字符串。 child2 在这个 topSchema 中存储了 topSchema 的 id 和 child1 的索引。

现在,我想向 child2 添加一个虚拟,它从 child1 返回相应的字符串。例如,我有以下 child2:

{
  topSchema: 1,
  child1Index: 2
}

以及以下 child1/topSchema 实例:

{
  _id: 1,
  child1: ["one", "two", "three", "four", "five"]
}

现在,child2 的 virtual 应该返回“three”,因为 topSchema 的 id 为 1,而“three”在 child1 数组中的索引为 2。

有人知道我是否或如何使用猫鼬中的虚拟字段来做到这一点?

0 个答案:

没有答案
相关问题