首页 > 解决方案 > 在查询中访问 MongoDB 子文档字段(Typescript 和 Mongoose)

问题描述

我使用猫鼬作为 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 而我并不是真正的强类型

标签: mongodbtypescriptmongoose

解决方案


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


推荐阅读