从嵌套 json 中查找猫鼬集合中的值

Find value inside a collection in mongoose from nested json

假设我将数据存储在集合 Teacher 中为:

{
    "name":"john",
    "age":45,
    "class_access":{
        1234:"head",
        1235:"head
    },
    "_id" : ObjectId("12312312"),
}

{
    "name":"henry",
    "age":55,
    "class_access":{
        1234:"head",
    },
    "_id" : ObjectId("sdf9991"),
}

{
    "name":"travis",
    "age":35,
    "class_access":{
        2341:"head",
    },
    "_id" : ObjectId("sas21"),
}

我要查找属于class1234的所有老师的所有信息

为此我尝试了:

 const TeacherDetails = await Teacher.find({ class_access: {1234:"head"} })

但它 return 什么都没有。 那么如何访问嵌套 json 以获取所有详细信息?

如果有人需要任何进一步的信息,请告诉我。

根据阿里夫先生提供的解决方案 const TeacherDetails = await Teacher.find({ "class_access.1234": "head" });

支持class值不是常量说我是从变量中获取的

const className = 1234

现在,如果我尝试获取 className,它会给出语法错误,我尝试了所有这些语法错误

const TeacherDetails = await Teacher.find({ class_access.className: "head" });

const TeacherDetails = await Teacher.find({ class_access[className]: "head" });

const TeacherDetails = await Teacher.find({ 'class_access.+'${className}': "head" });

那么我们如何才能动态地做到这一点呢?

因为class_access表示可能有多个键的对象,你应该试试

您可以使用 [variableName] 作为键,如下所示

方法一:使用字符串模板

const className = 1234
const TeacherDetails = await Teacher.find({ [`class_access.${className }`]: "head" });

方法二:使用字符串拼接

const className = 1234
const classAccess = 'class_access.' + className;
const TeacherDetails = await Teacher.find({ [classAccess] : "head" });