我使用以下代码收到了来自“请求”的响应:
collection.distinct('id', (err, docs) => {
docs.forEach(id => {
let url = 'url.com/id=' + id
request(url, (error, response, body) => {
var resp = JSON.parse(response.body.replace('._', '_'));
collection2.insert(resp);
});
});
});
response.body 返回一个字符串化的 JSON,其中一些字段和属性包含句点,例如:
MISC._EXTERIOR_FEATURES": {
"id": 29,
"name": "MISC._EXTERIOR_FEATURES",
"attributes": {
"ROOF_RACK": {
"id": 0,
"name": "ROOF_RACK",
"value": "roof rack"
}
}
代码解释:对于集合中的每个不同的 id,请求 id 的 url。然后,使用response.body(字符串),我使用.replace()来“清理”字符串化的JSON,然后解析它,并将其插入到collection2中。
错误:
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 33): Error: key MISC._EXTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 34): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 35): Error: key MISC._EXTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 36): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 37): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 38): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 39): Error: key MISC._EXTERIOR_FEATURES must not contain '.'
最佳答案
不确定为什么键不能包含“.”,但您的“替换”仅替换第一次出现的情况。尝试正则表达式。
.replace(/\._/g, '_')
关于javascript - MongoDB 有问题的 JSON prop/field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44034032/