I am creating a dynamic filter object for querying data from mongodb in nodejs. However mongo throws error "Failed to parse filter object, filter must be of BSON type object". Here is my reference function code and screen shot of logs.
function GetDeviceByFilter(args, cb) {
var query = args.qs;
var andQry = [];
var orQry = [];
var type = parseInt(query.type);
try {
if(type === uType.s){
andQry.push({sel: parseInt(query.idx)});
if(query.isSold === "0"){
orQry.push({uid: {$exists: false}})
orQry.push({uid: 0});
orQry.push({uid: null});
} else if(query.isSold === "1"){
orQry.push({uid : {$gt: 0}});
}
} else if(type === uType.a){
andQry.push({admn: parseInt(query.idx)});
if(query.isSold === "0"){
orQry.push({sel: {$exists: false}})
orQry.push({sel: 0});
orQry.push({sel: null});
} else if(query.isSold === "1"){
orQry.push({sid : {$gt: 0}});
}
}
logger.debug("And filter ", JSON.stringify(andQry));
logger.debug("or filter ", JSON.stringify(orQry));
} catch (e) {
logger.error(e);
}
var filter = [];
filter.push({$and: andQry});// = [$and : {andQry}, {$or: orQry}];
logger.debug("filter : ",filter);
var projections = {
uuid: 1,
mac: 1,
sim: 1,
imei: 1,
_id: 0
};
dbClient.FindDocFieldsByFilter(devCollection, filter, projections, 0,
function(e, d) {
if(e) logger.error(e)
cb(d, retCode.ok);
});
}
Tons of thanks in advance.
The BSON data type is the binary representation of a JSON data type format for serializing JSON documents. When you insert JSON documents through the wire listener with MongoDB API commands, a BSON column that is named data is created in the specified collection.
Field Types. MongoDB stores underlying document data using BSON types, and Mongoid converts BSON types to Ruby types at runtime in your application. For example, a field defined with type: :float will use the Ruby Float class in-memory and will persist in the database as the the BSON double type.
An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running.
Your filter
variable is an array, not an object and a find()
query accepts an object, not an array. Your final filter
object should have this structure, for example
var filter = {
"$and": [
{ sel: parseInt(query.idx) },
{ admn: parseInt(query.idx)}
],
"$or": [
{ uid: {$exists: false} },
{ uid: 0 },
{ uid: null}
]
}
So you need to change the part
var filter = [];
filter.push({$and: andQry});// = [$and : {andQry}, {$or: orQry}];
logger.debug("filter : ",filter);
to
var filter = {};
filter["$and"] = andQry;
filter["$or"] = orQry;
logger.debug("filter : ",filter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With