How can I know in mongodb if a field is a Date type?
date, mongodb, node.js
Solution
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 `getTypeMembers` works 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:
exports.getTypeMembers = function(obj) {
for(var _k in obj){
if (_k =="_id") continue;
if (Object.prototype.toString.call(obj[_k]) === "[object Number]"){
obj[_k] = "Number";
}else if (Object.prototype.toString.call(obj[_k]) === "[object String]"){
obj[_k] = "String";
}else if (Object.prototype.toString.call(obj[_k]) === "[object Date]"){
obj[_k] = "Date";
} else 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])[0].toUpperCase() + (typeof obj[_k]).slice(1);
}
}
return obj;
};
In the Mongo console part, I only can get the type doing the following:
db.user.find({},{myDate:1}).forEach(function(f) { print (f.myDate instanceof Date) } );
But If I do,
typeof db.user.myDate --> It returns "Object"
db.user.myDate instanceof Date --> It returns "false"
I still don't undertand why.
Problem
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?