简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z:如何获取其子文档包含值的文档(多对一关系)

[英]Mongoose: How to get documents that their subdocument includes a value ( Many to one relationship )

I have a situation that i need to filter users based on their Profession, here is how the User Schema is defined:我有一种情况,我需要根据他们的职业过滤用户,这是用户模式的定义方式:

const userSchema = new mongoose.Schema(
  {
    userData: {
      professions: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Profession'
        }
      ]
    }
  }
)

and here we have for Professions schema:这里我们有专业模式:

const ProfessionSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
    }
  }
)

How can I get a list of users that have a profession with an id of 5f8ea4396586f1168ab3a298 for example?例如,如何获取具有5f8ea4396586f1168ab3a298的职业的用户列表?

I tried我试过了

User.find({
    "userData.professions": { $elemMatch: $in: ["5f8ea4396586f1168ab3a298"] }
})

But seems like this is the opposite of what I'm trying to do.但这似乎与我正在尝试做的相反。 I need to get a result like this when I filter results based on 5f8ea4396586f1168ab3a298 as id of profession当我基于5f8ea4396586f1168ab3a298作为职业 ID 过滤结果时,我需要得到这样的结果

[
    {
        "name": "John Doe",
        "userData": {
            "professions": ["5f8ea4396586f1168ab3a298", "5f8ea4226586f1168ab3a296"]
        }
    },
    {
        "name": "John Smith",
        "userData": {
            "professions": ["5f8ea4396586f1168ab3a298",]
        }
    },
    {
        "name": "Elon Musk",
        "userData": {
            "professions": ["5f8ea4466586f1168ab3a29a", "5f8ea4396586f1168ab3a298", "5f8ea4146586f1168ab3a295"]
        }
    }
]

You just need to convert your professions id type string to object type using mongoose.Types.ObjectId , second you missed {} braces after $elemMatch ,您只需使用mongoose.Types.ObjectId将您的职业 id 类型字符串转换为 object 类型,第二次您错过了$elemMatch之后的{}大括号,

let professions = ["5f8ea4396586f1168ab3a298"];
professions = professions.map(profession => mongoose.Types.ObjectId(profession));
User.find({
  "userData.professions": { $elemMatch: { $in: professions } }
})

Playground操场


Second option, If you are matching single profession then this is alternative option,第二种选择,如果您匹配单一职业,那么这是另一种选择,

let professions = "5f8ea4396586f1168ab3a298";
User.find({
  "userData.professions": professions }
})

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM