3

I am having trouble finding information online as how to use Mongo ObjectID instances on the front-end.

I can't answer these questions:

(1) is it safe to serialize/deserialize ObjectID objects to/from JSON?

(2) How can I require the ObjectID module with AMD/RequireJS on the front-end?

(3) Is it better to just use strings on the front-end and just convert strings to ObjectIDs on the backend?

So yes I am having trouble working with and manipulating ObjectID objects on the frontend because I don't have the ObjectID module on the frontend, or at least this is a perceived problem. I haven't seen any examples of how to do this nor have I seen much talk of it online at all. Perhaps I am not approaching the problem correctly.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    Most of the time, your MongoDB driver, or your JSON library will convert the ObjectID to a string for you. –  Aug 05 '15 at 06:19

1 Answers1

1
  1. No. Your JSON parser will likely fail, as JSON only stores certain datatypes, and ObjectID isn't one of them...

    Although, note that if you're stringifying your data it is possible that your MongoDB driver would in fact back this by returning a string from the ObjectID... Here is an example in NodeJS:

    var ObjectID = require("mongodb").ObjectID,
        myObject = {test:ObjectID("55153a8014829a865bbf700d")};
    
    console.log(JSON.stringify(myObject));
    // {"test":"55153a8014829a865bbf700d"}
    
  2. No. I'm not sure there are any modules out there yet that give the ability to use ObjectID's in browser JS. Although perhaps you can port this NodeJS to browser JS compatibility?

  3. Yes. For now, I would say yes. You can just use the string on the front-end; although, like I said ealier, if you can port the ObjectID peice to be browser compliant (which shouldn't be too hard), I don't think there would be any issues there.