Mongo / Mongoose键替换

时间:2017-03-21 12:08:57

标签: node.js mongodb mongoose

我需要保存一个json对象,如:

{
   "name": "larry",
   "mapping": {
      "foo.bar": "bar"
   }
}

但是,Mongo禁止您保存其中包含$.的密钥 - reference

为了解决这个问题,我制作了一个实用程序来替换点unicode \uff0e

  export function replaceDots(obj, replace = true) {
    if(obj === undefined || obj === null) return obj;

    if(Array.isArray(obj)) {
      const result = [];

      for(const val of obj) {
        result.push(this.replaceDots(val, replace));
      }

      return result;
    } else if(typeof obj === 'object') {
      const keys = Object.keys(obj);
      const result = {};

      for(const key of keys) {
        let newKey;
        if(replace) {
          newKey = key.replace(/\./g, '\uff0e');
        } else {
          newKey = key.replace('\uff0e', '.');
        }

        const val = obj[key];

        result[newKey] = this.replaceDots(val, replace);
      }

      return result;
    }

    return obj;
  }

我可以肯定unicode永远不会出现在这些密钥中,所以它对我的用例来说是一种安全的方法。但是,现在我现在无论在哪里获取或保存模型,我都必须将其转换为:

const newPlaybook = replaceDots(request.body);

const playbook = new Playbook(newPlaybook);

let result = await playbook.save();

result = replaceDots(result, false);

这是非常讨厌和容易出错的,我尝试使用中间件和toJSON函数来进行转换,但因为我实际上正在返回一个新对象,所以它不是很成功。

我想知道是否有更好的方法来处理这个问题,而不必在每次使用时手动调用替换?

0 个答案:

没有答案