【问题标题】:Search mongodb array for field value on dropdown change在下拉列表更改时搜索 mongodb 数组以获取字段值
【发布时间】:2015-09-09 06:11:56
【问题描述】:

我有一个下拉菜单需要为 Mongo 中的特定文档触发 findOne。我希望它只返回找到值的数组。

下拉html:

<select class="form-control" id="saved_config" name="saved_config">
    {{#each currentUser.profile.saved_configs}}
        <option value="{{config}}">{{config}}</option>
    {{/each}}
</select>

这会从当前用户配置文件部分中的每个“saved_configs”数组中提取“config”字段值。

下拉js:

"change #saved_config": function(event, template) {
    var selected = $( "#saved_config option:selected" ).text();
    var search = Meteor.users.findOne({_id:Meteor.user()._id}, {'profile.saved_configs.$' : selected});

    console.log(search)

},

监听下拉列表的变化并找到一个带有当前用户 id 的“_id”的文档,并在“saved_configs”中的所有数组中搜索下拉选择的文本。

问题在于,无论我将“profile.saved_configs.$”设置为什么值,它都会返回整个文档。我还希望它只返回在其中找到下拉文本的数组。这样我可以轻松地检索同一数组中的其余值。

这是文档架构 -

  • _id:

  • 简介:

    • 保存的配置:
      • [数组]
      • [数组]

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    我想你在找this functionality

    但是,流星文档指出:Field operators such as $ and $elemMatch are not available on the client side yet.

    但是,由于您在客户端上有完整的文档,因此在 javascript 中选择正确的数组应该很简单。即使您有 Field Operator 支持,这一切都发生在客户端(并且您不会从服务器请求额外数据),因此据我所知,在 javascript 中执行此操作没有任何缺点。

    我在猜测 saved_configs 中项目的结构,但代码应该是这样的:

    "change #saved_config": function(event, template) {
      var selected = $( "#saved_config option:selected" ).text();
      var _search = Meteor.users.findOne({_id:Meteor.user()._id});
      var search = _search.profile.saved_configs.filter(
           function(config){ 
             return config.name === selected;
           })[0]     // .filter returns array, select first (only) item
      console.log(search)
    },
    

    【讨论】:

    • 效果很好!我不知道 $elemMatch 还没有在客户端可用。我也在尝试使用它。
    猜你喜欢
    • 2020-07-13
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2014-06-28
    • 2017-03-12
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    相关资源
    最近更新 更多