0

I want to be able to store objects as code in mongo DB. the main problem is when trying to store an array that contain types.. Example: [String, Array, 'some', 'hello world']. When saving and getting the document I would get

Doc.array = [undefined, undefined, 'some', 'hello world']

Is there a way to serialize the array it self and save it in mongo ? Something like:

var S = require('serializer');
var obj = {
    cons: [[String, 'some', 'somemore']],
    func: function(param, param2){
        param2.some = 'bla';
    }
};

var objs = S.serializer(obj);

//Store that serialized obj as a value for binary key or buffer key in mongo..
// then when getting the document...

var obj = S.deserialize(objs);
// being obj the exactly same object with the array and the function.

Is there a way to do this, or is there a different/better approach ?

Edit

I just need a way to store a nools rule, so the problem is that the rule constraints structure is the following:

[FactType, 'alias', 'conditions']

Where FactType could be String, Object, Custom.

2
  • String is (or rather, refers to) a function. What exactly do you want stored in Mongo for it? Commented Nov 20, 2014 at 17:03
  • @T.J.Crowder take a look to my edit. Would be great if there is a way to serialize that but keep String just for a reference.. not the string function it self. Commented Nov 20, 2014 at 17:19

1 Answer 1

2

If It's Just A JSON You Can stringify A Json :

var text=JSON.stringify(obj);

And Parse To Jason Again By parse :

var myVar=JSON.parse(text);

If You Have Functions In The Object Use This To Serialize:

function objToString(obj, ndeep) {
  switch(typeof obj){
    case "string": return '"'+obj+'"';
    case "function": return obj.name || obj.toString();
    case "object":
      var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
      return ('{['[+isArray] + Object.keys(obj).map(function(key){
           return '\n\t' + indent +(isArray?'': key + ': ' )+ objToString(obj[key], (ndeep||1)+1);
         }).join(',') + '\n' + indent + '}]'[+isArray]).replace(/[\s\t\n]+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/g,'');
    default: return obj.toString();
  }
}

Example

Serialize:

var text=objToString(obj); //To Serialize Object

Result:

"{cons:[[String,"some","somemore"]],func:function(param,param2){param2.some='bla';}}"

Unserialize:

Var myObj=eval('('+text+')');//To UnSerialize 

Result:

Object {cons: Array[1], func: function, spoof: function}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.