[英]How to insert JSON object with “$” field into Meteor collection?
我正在從Amazon API檢索有關書籍的數據,並將其存儲為JSON對象。 然后,我想將此數據插入到Meteor集合中。 但是,JSON數據中的某些字段以“ $”字符開頭,從而導致此錯誤:
MongoError:“ result.results.0.ItemAttributes.0.ManufacturerMaximumAge.0。$”中以美元($)為前綴的字段“ $”對存儲無效。
鑒於數據包含“ $”符號,我希望將數據插入集合中。 如果不可能,是否有辦法刪除JSON數據中所有出現的“ $”,然后將其存儲到Meteor集合中? 這是我的代碼,具有書名和作者名,該代碼搜索Amazon API並返回有關前10個結果的信息:(SearchResult是對該集合的引用)
Meteor.methods({
itemSearch(appUUID,title, author) {
var result = {};
result.search = {
appUUID: appUUID,
title: title,
author: author
}
client.itemSearch({
title: title,
author: author,
searchIndex: 'Books',
responseGroup: 'ItemAttributes, Images'
}).then(function(results){
result.results = results;
var upsertResult = SearchResult.upsert( {
appUUID: appUUID,
title: title,
author: author,
},
{
$set: {result: result}
}
);
}).catch(function(err){
SearchResult.upsert({
appUUID: appUUID,
title: title,
author: author,
},
{
$set: {result: result }
}
);
});
}
});
這是JSON數據,導致此問題的原因是“單位”前的美元符號。
"Width": [
{
"_": "810",
"$": {
"Units": "hundredths-inches"
}
}
]
簡單的答案是,不,您不能使用MongoDB中的$
in字段(來自docs ):
字段名稱不能以美元符號($)開頭。
有很多可能的解決方案將數據更改為MongoDB可以接受的格式,但是要給您我能想到的最簡單的解決方案,您只需映射對象的鍵即可。 例如,使用lodash的mapKeys
函數 :
data = _.mapKeys(data, (value, key) => {
if(key === '$') {
return 'some_custom_key'
} else {
return key
}
})
這會將您的所有$
更改為some_custom_key
。 只要您具有掛鈎(例如Mongoose的save
前中間件和read
中間件docs )等可以在后台為您轉換的鈎子,它就應該是一個可行的解決方案。
我不知道是否可能,但是更好的解決方案是讓Amazon API在沒有$
的情況下$
您提供數據,但是由於我不熟悉該API,所以我無法對此進行推測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.