Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Json Object in Mongoose String key

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 in a string column.

I want to do that because the dictionary (actually a JSON object in JS) is just a simple read and write value and doesn't need queries, but also, because it is just one value and not an array of values.

like image 895
Saransh Mohapatra Avatar asked Jul 05 '13 23:07

Saransh Mohapatra


People also ask

Can we store JSON in string?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

Does JSON have to be key-value?

JSON objects are written in key/value pairs. JSON objects are surrounded by curly braces { } . Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon.

Can a JSON key be an object?

Each key/value pair is separated by a comma. It is a common mistake to call a JSON object literal "a JSON object". JSON cannot be an object. JSON is a string format.


2 Answers

Yes, you can just store {myJsonProperty: JSON.stringify(myObject)}. Hopefully you know that you can also just set {myJsonProperty: Object} in your mongoose schema and store the whole object without converting it to a string for no reason. It doesn't have to be a nested document with a schema, it can be just a plain javascript object.

like image 56
Peter Lyons Avatar answered Oct 02 '22 07:10

Peter Lyons


if you can change the type of your field form "String" to "Object" you can save the json as it is.

var schema_obj = new Schema({
field1: Object,
..
});
like image 20
dam1 Avatar answered Oct 02 '22 05:10

dam1