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
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);
}
}