Storing Json Object in Mongoose String key

前端 未结 5 803
温柔的废话
温柔的废话 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 04:47

    We needed to retain structure and not do a string so I came up with the following methods to handle this:

    const setMongoMixedWithBadKeys = data =>
      Array.isArray(data)
      ? data.map(setMongoMixedWithBadKeys)
      : typeof data === 'object' 
      ? Object.entries(data).reduce((a, [key,value])=>({...a, [key.replace('.','__').replace('$','___')]:setMongoMixedWithBadKeys(value)}), {})
      : data
    
    const getMongoMixedWithBadKeys = data =>
      Array.isArray(data) 
      ? data.map(getMongoMixedWithBadKeys) 
      : typeof data === 'object'
      ? Object.entries(data).reduce((a, [key, value])=> ({...a, [key.replace('__','.').replace('___','$')]:getMongoMixedWithBadKeys(value)}), {})
      : data
    
    
    data: {
      type: Mixed,
      get:  getMongoMixedWithBadKeys,
      set:  setMongoMixedWithBadKeys
    }
    

提交回复
热议问题