0

My application is based on Node.js and MongoDB using rest api.

My input data is in the form

   var doc={"name":"ABX", duedate : new Date() } 

I'm stringifying it before passing it to the server

    /rest/update?doc=JSON.stringify(doc) 

and converting it back to JSON on server side as :

    var doc = JSON.parse(doc)

Now the issue is that it stringifies the data as :

    var doc = {"name":"ABX","duedate":"2014-04-30T18:30:00.000Z"}

If same value send to mongo, then it will save duedate as string. So need to do something like doc.duedate = new Date(doc.duedate). But I do not have any field definition, So how I know some field need to be converted to date and some not.

Similar is case when working with _id field of MongoDB.

My client side generates _id for document in 2 ways :

1 : _id:"student1" -> String type that is user specified

2: _id:535f7d05e1b08ddc13dfbaf0 -> ObjectId type generated by mongoDB.

For second type _id, when it is passed from client side it will be a string not a objectid. For both type of doc, user will send query something like /students/find?query={_id:"student1"} OR {_id:"535f7d05e1b08ddc13dfbaf0"} . Now at server second query must be modified as {_id: ObejctId("535f7d05e1b08ddc13dfbaf0")}.

I don't know how to distinguish between two.

Major issue I am facing is the datatype lost between sending doc from client side to server side in JSON

Now I'm wrapping it up in string form on client side and can convert it back on server side.

Since mongoDB isn't type specific i don't know what value i should convert on client side and what not.

Both user-defined and Self-generated are received on server side as String-type which makes re-converting a tough job.

My requirement is that i don't want conversion on server side.

  • Client can send either Object or String and it should be stored as is on backend.

Is this possible in any way ?

vashishatashu
  • 7,720
  • 7
  • 29
  • 34
  • You can convert it with: `var doc = JSON.parse(doc); doc.duedate = new Date(doc.duedate);`, but you may want to [look at this post](http://stackoverflow.com/questions/3778428/best-way-to-store-date-time-in-mongodb) as well. –  May 02 '14 at 13:06
  • @TimCooper I have updated my question. Do take a look again. – vashishatashu May 02 '14 at 13:52

1 Answers1

1

You can't, from the JSON RFC:

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

You have to parse the date after sending it to the server:

var doc = JSON.parse(doc);
doc.duedate=new Date(doc.duedate);
Michael
  • 1,322
  • 11
  • 17
  • Thanks Michael, AS mongo does not required field definition, in the similar way in my application ,I want to give user free hand support means they can insert what they want. No field definition required, So how I will be enable to know that a particular field need to be converted into Date or not. – vashishatashu May 03 '14 at 04:01