【问题标题】:Accessing MongoDB subdocument fields in query (Typescript and Mongoose)在查询中访问 MongoDB 子文档字段(Typescript 和 Mongoose)
【发布时间】:2020-06-30 17:55:14
【问题描述】:

我使用猫鼬作为 ODM。假设我有这种方案结构。

const Child = new mongoose.Schema({
    field1: {
      type:String
    },
    field2: {
      type:String
    }
});


const Parent = new mongoose.Schema({
  children: {
    type: [Child]
  },
});

interface IChildDoc extends mongoose.Document {
   field1: string
   field2: string
}

interface IParentDoc extends mongoose.Document {
   children: [IChildDoc]
}

const ParentModel = mongoose.model<IParentDoc>("Parent", Parent)

我想通过field1查询,但是像这样:

const parent = await ParentModel.findOne({children.field1 : "string"});

但我得到了:

No value exists in scope for the shorthand property 'children'. Either declare one or provide an initializer.

我也尝试将children.field1 放在一个字符串中,但这只会导致返回 null 而 I 并不是真正的强类型

【问题讨论】:

  • 嵌入文档使用点符号查询,包含点的字段需要引用。你的问题到底是什么?
  • 那么有没有办法以静态类型的方式做到这一点?
  • 我不认为这是可能的。

标签: mongodb typescript mongoose


【解决方案1】:

你必须这样查询:{"children.field1" : "string"}

【讨论】:

  • 是的,我知道,但我正在寻找静态类型的解决方案
  • 我认为没有类型化的解决方案。
猜你喜欢
  • 2020-08-02
  • 2018-04-05
  • 2019-07-27
  • 2018-12-01
  • 2015-12-20
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多