【发布时间】:2018-04-19 09:58:01
【问题描述】:
想再次向您学习 Node.js 和 mongoose。
我定义了一个猫鼬模式,findOne() 返回一个文档,如下所示。实际文档中的“资源”下还有很多元素。
{
"metadata": {"isActive": true, "isDeleted": false },
"test": "123",
"resource": {
"id": "59e94f3f6d5789611ce9926f",
"resourceType": "Patient",
"active": true,
"gender": "male",
"birthDate": "2000-01-01T00:00:00.000Z",
"extension": [
{
"url": "hxxp://example.com/fhir/StructureDefinition/patient-default-bundle",
"valueCodeableConcept": {
"code": "sys",
"display": ""
}
}
],
"link": [],
"careProvider": [],
"communication": [],
"animal": {
"genderStatus": {
"coding": []
},
"breed": {
"coding": []
},
"species": {
"coding": []
}
},
"contact": []
}
}
问题:如何选择“资源”下的所有非空字段?
我的预期结果如下,即“资源”元素下的所有非空字段。
{
"id": "59e94f3f6d5789611ce9926f",
"resourceType": "Patient",
"active": true,
"gender": "male",
"birthDate": "2000-01-01T00:00:00.000Z",
"extension": [
{
"url": "hxxp://example.com/fhir/StructureDefinition/patient-default-bundle",
"valueCodeableConcept": {
"code": "sys",
"display": ""
}
}
]
}
我目前的编码:
module.exports.findById = function (req, res, next) {
var resourceId = req.params.resourceId;
var resourceType = req.params.resourceType;
var thisModel = require('mongoose').model(resourceType);
console.log("findById is being called by the API [" + resourceType + "][" + resourceId + "]");
thisModel.findOne(
{'resource.id': resourceId, 'metadata.isActive': true, 'metadata.isDeleted': false},
'resource -_id',
function(err, doc) {
if (err) {
globalsvc.sendOperationOutcome(res, resourceId, "Error", "findOne() Not Found", err, 404);
}
else {
if (doc) {
sendJsonResponse(res, 200, doc);
} else {
delete doc._id;
globalsvc.sendOperationOutcome(res, resourceId, "Error", "Id: [" + resourceId + "] Not Found", err, 404);
}
}
}
);
}
【问题讨论】:
-
你的意思是所有没有空数组属性的东西?如“返回文档但如果为空则不显示这些属性”?如果这是您的要求,那么它实际上根本不是很简单。最好的情况是根本不存储该属性,除非您有一些数据要放入其中。这比剥离服务器返回的属性要容易得多。
-
谢谢尼尔,我想要“资源”下的所有内容,这些内容不为空。此外,资源: { } 也需要删除。请看我的预期结果。我同意你的观点,首先不应该存储那些空字段。例如,文档是 { 'resource': { 'id': '123', 'gender': ""}},我的预期结果是 {'id': '123'} 因为 'gender' 为空。
-
这就是我以为你的意思。这不是一件简单的事情。作为一个“无模式”的面向文档的存储,一般的意图是如果你没有属性的数据,那么你根本不存储它。存储空字符串或空数组实际上是“某事”。并且它需要使用聚合框架进行非常先进的计算密集型投影,以便在返回结果之前“删除”这些投影。所以这里的一般建议是“不要存储空属性”,如果您不希望它们返回。
-
嗨,尼尔,再次感谢。你说的对。我不应该保存那些空字段。是否有任何好的示例代码可以检查空字段并以通用递归方式删除它们? ;) 我有几个非常复杂和深刻的模式。
-
嗨,尼尔,不管是否为空,都返回“资源”下的所有字段如何?如何以简单的递归方式提取“资源”下的所有字段?
标签: javascript node.js mongodb mongoose