从mongo返回的对象(findOne)中筛选/返回单个嵌套对象

Filtering/Returning a single nested object from mongo returned object (findOne)

本文关键字:返回 对象 筛选 单个 嵌套 findOne mongo      更新时间:2024-04-21

尽管围绕这个主题还有一些问题,但我还没有找到一个明确的通用"最佳实践"来过滤返回的流星mongo收集对象。

(仅供参考:我正在使用MeteorJS)

我从configs集合中提取了一个配置文档。

let thisConfig = ClinicConfigs.findOne({_id: "xyz"});

这已经返回了以下

{
    _id: "xyz",
    name: "john doe's clinic",
    activeServices: [
         {
             name: "teeth whitening",
             ref: "teethWhitening",
             docs: [
                 {
                     docId: "a",
                     name: "Client questionnaire",
                     ref: "clientQuestionnaire",
                 },
                 {
                     docId: "b",
                     name: "Client consent form",
                     ref: "clientConsentForm",
                 }
             ]
         },
         {
             name: "liposuction",
             ref: "liposuction",
             docs: [
                 {
                     docId: "a",
                     name: "Client questionnaire",
                     ref: "clientQuestionnaire",
                 },
                 {
                     docId: "b",
                     name: "Client consent form",
                     ref: "clientConsentForm",
                 }
             ]
         }
    ];

一旦我返回了这个文档/对象,我只需要从activeServices数组中提取一个对象。

虽然这不起作用,但以下是澄清我需要的逻辑:

let thisService = ClinicConfigs.findOne({_id: "xyz"})
        .activeServices.findOne({ref: "teethWhitening"});

我尝试了以下操作,但没有成功:

let thisConfig = ClinicConfigs.findOne({_id: "xyz"});
let thisService = thisConfig.activeServices.filter(function(d) {return d.ref === "teethWhitening"})[0];
return thisService.docs;

它可以工作,但我不得不用后面的大括号更正您的thisConfig数据对象。所以一旦它像

var thisCongig = {
    _id: "xyz",
    name: "john doe's clinic",
    activeServices: [
         {
             name: "teeth whitening",
             ref: "teethWhitening",
             docs: [
                 {
                     docId: "a",
                     name: "Client questionnaire",
                     ref: "clientQuestionnaire",
                 },
                 {
                     docId: "b",
                     name: "Client consent form",
                     ref: "clientConsentForm",
                 }
             ]
         },
         {
             name: "liposuction",
             ref: "liposuction",
             docs: [
                 {
                     docId: "a",
                     name: "Client questionnaire",
                     ref: "clientQuestionnaire",
                 },
                 {
                     docId: "b",
                     name: "Client consent form",
                     ref: "clientConsentForm",
                 }
             ]
         }
    ]
};
var thisService = data.activeServices.find( d => d.ref == "teethWhitening");

并且它被取回。