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.
CodePudding user response:
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);
CodePudding user response:
Find expected values in the particular date range to get an output by using Find() Keyword , to get all the array of listed outputs use All()
db := GetDB()
defer db.Session.Close()
var tempMeet []models.Meetings
gtQuery := bson.M{"$gt": start}
ltQuery := bson.M{"$lt": end}
pipe := bson.M{
"$and": []bson.M{
bson.M{"startTime": gtQuery},
bson.M{"endTime": ltQuery},
},
}
shared.BsonToJSONPrint(pipe)
err := db.C(models.COLLECTIONNAME).Find(pipe).All(&tempMeet)
if err != nil {
fmt.Println(err)
return nil, errors.New(err.Error())
}
return tempMeet, nil