用猫鼬在嵌套数组中查找值

时间:2020-07-16 14:36:03

标签: javascript node.js mongoose

我有以下架构:

const ClientManagerSchema = new Schema({
    name : { type : String,  required : true},
    project : [ProjectSchema]
});

一个项目看起来像这样:

const ProjectSchema = new Schema({
    companyName : {type: String , required : true}, 
    projectName : String, 
    projectManager : String, 
    projectManagerUrl : String, 
    employees : [], 
    contactPerson : [], 
    employeeInfo : [], 
    projectHours : [], 
    trelloUrl : String, 
    dataStudioUrl : String,
    projectUrl : String,
    AnalyticsEmail : String,
    companyId : String,
    projectId : String,
    total : Number,
    totalIn : Number,
    totalSt : Number,
    totalSale : Number,
    earliestDate : String, 
    firstEvaluation : String,
    secondEvaluation : String, 
    firstEvaluationIndex : Number,
    secondEvaluationIndex : Number,
    revenueGroups : [RevenueGroupSchema],
    revenueGroupsIn : [RevenueGroupSchema],
    revenueGroupsSt : [RevenueGroupSchema],
    sales : [RevenueGroupSchema],
    saleData : [],
});

我想从数据库中选择所有公司名称为“ test bv”的文档。但是由于项目的价值是嵌套的,所以我不确定该怎么做。我还可以将值提升到可以轻松访问的水平,但这并不是最佳选择。

我尝试了一些行不通的事情:

ClientManager.find({'companyName': 'test bv'}).then((res) => console.log(res)).catch(err => console.log(err))

这给了我一个空数组。

2 个答案:

答案 0 :(得分:2)

将此find({'companyName': 'test bv'})更改为此find({'project.companyName': 'test bv'})

答案 1 :(得分:1)

ClientManager.find({'project.companyName': 'test bv'}).then((res) => console.log(res)).catch(err => console.log(err))