【问题标题】:Return Array from Embedded document从嵌入式文档返回数组
【发布时间】:2017-06-09 07:30:28
【问题描述】:

我有一个类似 mongodb 集合名称属性的数据。

{
            "_id": "593a3d828e2ef100d1496e77",
            "feature_type": "house",
            "features": [
                {
                    "name": "h1"
                },
                {
                    "name": "h2"
                }
            ]
        }

我只想要

 [
            {
                "name": "h1"
            },
            {
                "name": "h2"
            }
        ]

结果我尝试了这个

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1});

这个给

{
    "_id": "593a3d828e2ef100d1496e77",
    "features": [
        {
            "name": "Hotel"
        },
        {
            "name": "Apartment"
        }
    ]
}

我该怎么做才能得到上面给出的结果。

【问题讨论】:

  • 真的不要尝试。照原样使用它。它没有任何问题,并且这样做的唯一方法会增加处理成本。简单的查询很快。所以接受这是你获取它的方式,只需通过返回结构中提供的路径访问数组。
  • @NeilLunn 我将公开 api,因此返回的结构也是一个重点。 :)
  • 注意你得到的答案。每个人都在告诉您从返回的文档中访问该属性。这是正确的做法。不要要求数据库这样做,因为它确实不应该这样做。如果您想要单独的内容,那么它不应该是嵌入文档。
  • 是的,我正在考虑这个

标签: node.js mongodb mongodb-query embedded-database embedded-documents


【解决方案1】:

您必须从投影中排除 _id,如下所示:

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1, _id:0});

【讨论】:

    【解决方案2】:

    假设您使用的是像猫鼬that returns promises 这样的东西,您可以使用查询的结果

    return req.db.collection('FeatureSettings')
    .findOne({feature_type: req.params.feature_type}, {features: 1})
    .then((result) => {
        return result.features;
    });
    

    【讨论】:

    • 我没有使用猫鼬
    【解决方案3】:

    您可以尝试仅返回 features 数组值。

    req.db.collection('FeatureSettings')
     .findOne({feature_type: req.params.feature_type}, {features:1, _id:0}).features;
    

    // if you use mongoose can use 
    return req.db.collection('FeatureSettings')
      .findOne({feature_type: req.params.feature_type}, {features:1, _id:0})
      .exec()
      .then((result) => {
         return result.features;
      });
    

    【讨论】:

    • 我没有使用猫鼬。
    • 第二部分适用于mongoose,但第一部分应该适用于native mongodb @manoj
    猜你喜欢
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2012-04-12
    • 1970-01-01
    相关资源
    最近更新 更多