I’m working on a NodeJS+Mongodb app.
I’ve just inserted one record into mongodb using the console client:
db.user.save({myId:11111, myDate: ISODate("2012-04-30T00:00:00.000Z")})
The thing is, when I’m in node.js, I need to know if “myDate” field is really a Date type, in order to perform a data range query, etc.
I tried the following.
1. on the mongo client console:
typeof db.user.myDate --> It returns "Object"
db.user.myDate instanceof Date --> It returns "false"
2. on my Nodejs code,
I’m trying to get the type calling this getTypeMembers function. (obj comming from a db query)
exports.getTypeMembers = function(obj) {
obj = JSON.parse(JSON.stringify(obj)
for(var _k in obj){
if(Object.prototype.toString.call(obj[_k]) === '[object Array]' ) {
obj[_k] = "Array";
}
else if(typeof(obj[_k])=="object"){
obj[_k] = this.getTypeMembers(obj[_k]);
}else{
obj[_k] = typeof (obj[_k]);
}
}
return obj;
};
What I get in this method is: "String", when I need "Date"
Is there any other way to get some kind of "Date" result?
I finally found my solution.
As @christkv said, once you call a JSON stringify, all original types are definitely lost.
So, thinking in this way, my method
getTypeMembersworks perfectly for me.Notice that, obj parameter is coming from the DB, and also “_id” (mongodb identificator) is directly ommited in order to avoid problems when performs the recursive function:
In the Mongo console part, I only can get the type doing the following:
But If I do,
I still don’t undertand why.