【问题标题】:How to insert JSON object with "$" field into Meteor collection?如何将带有“$”字段的 JSON 对象插入 Meteor 集合?
【发布时间】:2017-03-20 09:17:43
【问题描述】:

我正在从 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"
             }
       }
 ]

【问题讨论】:

    标签: javascript mongodb amazon-web-services meteor


    【解决方案1】:

    简单的答案是,不,您不能在 MongoDB 的字段中使用 $(来自 the docs):

    字段名称不能以美元符号 ($) 字符开头。

    有许多可能的解决方案可以将您的数据更改为 MongoDB 可以接受的格式,但是为了给您我能想到的最简单的解决方案,您可以只映射对象的键。例如,lodash's mapKeys function:

    data = _.mapKeys(data, (value, key) => {
      if(key === '$') {
        return 'some_custom_key'
      } else {
        return key
      }
    })
    

    这会将您的所有$ 更改为some_custom_key。只要你有钩子(比如 Mongoose 的 pre save 中间件和 post read 中间件,docs)可以在后台为你转换它,它应该是一个可行的解决方案。

    我不知道这是否可能,但更好的解决方案是让 Amazon API 在没有 $ 的情况下为您提供数据,但我无法推测这一点,因为我不熟悉该 API。

    【讨论】:

    • 您好,抱歉耽搁了。我会试试这个并回复你。感谢您的快速回复!
    猜你喜欢
    • 2015-07-24
    • 2013-12-10
    • 2014-01-23
    • 2016-02-07
    • 2021-10-31
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多