如何 return json 中的子集合(或对象)而不包括所有属性

How to return a subcollection (or object) in json without including all attributes

我正在使用 mongoose 作为 JSON Schemanode.js。不用说,我对两者都是新手。我一整天都在努力让这件事为我工作,但做不到。最后,唯一的解决办法是从这里的一些真正的好人那里得到帮助。

这是我的架构定义 -

UserName = {    
        "properties": {
            userURL: {
                    "description": "URL of this resource",
                        "type": "string"
                },
            userName : {
                    "description": "UserName",
                    "type": "string",
                    "required": true
                },
        }
}

当我调用它时,它 return 的响应格式如下 -

[
  {
    "_id": "54c5ede55c82c4bd6abee50a",
    "__v": 0,
    "properties": {
    "userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
    "userName ": "testUser"
    }
  }
]

现在我的要求是 return 以下格式的响应 -

[
  {
    "_id": "54c5ede55c82c4bd6abee50a",
    "userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
    "userName ": "testUser"
  }
]

即没有版本和属性标签。我可以使用以下代码摆脱版本问题,但属性似乎很棘手 -

 .get(function(request, response) {
        UserSchemaModel.find().select('properties.userURL properties.userName').exec (function (err, resObj) {
            if (err)
                response.send(err);
            else{           
                response.json(resObj);
            }
        });
    });

但它仍然有属性字段:( -

[
 {
    "_id": "54c5ede55c82c4bd6abee50a",
    "properties": {
    "userURL": "http://localhost:3000/54c1d6ae441ae900151a6520",
    "userName ": "testUser"
    }
 }
]

我在 select asalias name in selectpopulation 周围用猫鼬做了一些 google,但运气不好。

请多多指教。此致。

只需创建一个新对象

response.json(
              {
               "_id":     resObj["_id"], 
               "userURL": resObj["properties"]["userUrl"], 
               "userName": resObj["properties"]["userName"]
              }
           );

更新: 由于 resObj 是一个数组(根据您的评论),您可以使用 Array.prototype.map() 将它们转换为正确的格式,如下所示:

response.json( resObj.map(function(o){
                 return {
                          "_id":      o["_id"], 
                          "userURL":  o["properties"]["userUrl"], 
                          "userName": o["properties"]["userName"]
                        };
                    }) 
                 );

这将 return 转换后的对象列表,然后传递到 response.json() 方法。