I have a problem bining UnderscoreJS and MongooseJS in NodeJS. I have a result of mongoose and I want filter a array
var __ = require("underscore"),
platformInfo = __.findWhere(user.platforms, {"pId": platformId});
But pId inside user.platforms is a ObjectId and can't find. But if i make a each and pare like this all its OK:
__.each(user.platforms, function(platform){
if(platform.pId.toString() == platformId){
}
});
How i can find in findWhere method (one line, and cool) the same result? Thanks
I have a problem bining UnderscoreJS and MongooseJS in NodeJS. I have a result of mongoose and I want filter a array
var __ = require("underscore"),
platformInfo = __.findWhere(user.platforms, {"pId": platformId});
But pId inside user.platforms is a ObjectId and can't find. But if i make a each and pare like this all its OK:
__.each(user.platforms, function(platform){
if(platform.pId.toString() == platformId){
}
});
How i can find in findWhere method (one line, and cool) the same result? Thanks
Share Improve this question asked Sep 9, 2013 at 15:11 user1710825user1710825 5885 silver badges15 bronze badges4 Answers
Reset to default 7Sadly mongodb ObjectId instances do not work properly with JavaScript's equality operators ==
or ===
. You either need to use the provided method: objectId1.equals(objectId2)
or ensure they are both converted to strings and then underscore or ===
will work.
platformInfo = _.filter(user.platforms, function (platform) {
return platform.pId.toString() === platformId;
})
I tried to write a general function for that problem using underscore.js:
function findWhereObjectId(objs, p) {
return _.find(objs, function(obj) {
return _.some(_.keys(obj), function(key) {
return (key == _.keys(p)[0] && obj[key].equals(p[key]));
});
});
};
You could now call findWhereObjectId(user.platforms, {"pId": platformId})
and it should give you the first match.
As mentioned before, mongodb ObjectId instances do not work properly with JavaScript's equality operators. However, there's another simpler solution for this problem: You could take your MongoDB result object and convert it to a string via JSON.stringify():
var myString = JSON.stringify(MONGODB_RESULT);
After that you can convert that string back to an object via JSON.parse():
var myObject = JSON.parse(myString);
You can now perform any Lodash/Underscore operation on that object.
Hope that helps!
You can use .toString after id of mongo response obbject For ex
_.findWhere(allMappingData, {_categoryId: catObj._id.toString() ,_contentId: content.contentId.toString()}));