Storing Json Object in Mongoose String key

前端 未结 5 801
温柔的废话
温柔的废话 2021-01-30 04:14

In my Mongoose schema, I have a field which is a String, and I want to be able to store an JSON object in it. Is it possible? In Postgres, it\'s possible to store a dictionary i

5条回答
  •  盖世英雄少女心
    2021-01-30 05:00

    The accepted answer is good for the majority of situations.

    However, if you have an object which you want to store, and you have no control over the object keys (e.g. they might be user-submitted), you might want to consider storing these as stringifed JSON. This allows you to overcome the limitation imposed by MongoDB that keys must not contain the reserved characters $ or ..

    You can achieve this using Mongoose getters and setters, for example:

    data: {
      type: String,
      get: function(data) {
        try { 
          return JSON.parse(data);
        } catch() { 
          return data;
        }
      },
      set: function(data) {
        return JSON.stringify(data);
      }
    }
    

提交回复
热议问题