Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17586

dynamically add fields to find() mongodb

Hi i am working with mongoDB , i am trying to crate a dynamic object and pass as an argument to the find()

my object is like this

Library

var search = {};
if(data.orderId) {

    search["_id"] = { $in: data.orderId.split(",") } ;
}if(data.path) {

    search["stops.districtId"] = data.path;
}if(data.special) {

    search["special.option"] = { $in: data.special.split(",") } ;
}if(data.userInfo) {

    search["UserId"] = data.userInfo;
}

then i will pass my search objet to the query like this

Model

                var col = db.collection( CustomerOrderModel.collection() );
                col.find(
                            {
                                serviceType:data.serviceType,
                                **search**
                            }
                    ).skip(data.skip).limit(data.limit).sort(data.sort).toArray(function(err, res) {

                    if (err) {

                        reject( err );
                    } else {

                        resolve( res );
                    }
                });

the problem here is when i console.log my search object i can see

'special.option': { '$in': [ 'ROUND_TRIP' ] } }

my $in is wrapped with quotes . so my query doesn't work .

if i directly type "special.option": { $in: [ 'ROUND_TRIP' ] } } in my query it is working correctly .

i m trying to built this search object because i have multiple fields to search with complex logic . i don't want to do these in my model , so i wil create the search object in my library .

is there any possible ways to this , thanks in advance .

Upvotes: 0

Views: 781

Answers (2)

bolav
bolav

Reputation: 6998

That is not the problem.

console.log({ "special.option": { $in: [ 'ROUND_TRIP' ] } });

gives

{ 'special.option': { '$in': [ 'ROUND_TRIP' ] } }

so this is correct.

In your code you just write **search** in the most critical part, but try this:

search["serviceType"] = data.serviceType;
col.find( search )

Upvotes: 1

chridam
chridam

Reputation: 103445

You should make the search object part of the query by adding the extra filters into the search object. As you are currently doing

col.find({
    serviceType:data.serviceType,
    search
})

this is interprated as

col.find({
    serviceType:data.serviceType,
    { 'special.option': { '$in': [ 'ROUND_TRIP' ] } } 
})

You should be able to add the serviceType filter to your existing search object using the square bracket notation as follows:

search["serviceType"] = data.serviceType;

then you can pass that object in your query:

var col = db.collection( CustomerOrderModel.collection() );
search["serviceType"] = data.serviceType;
col.find(search)
   .skip(data.skip)
   .limit(data.limit)
   .sort(data.sort)
   .toArray(function(err, res) {
        if (err) {  reject( err ); } 
        else {  resolve( res ); }
    });

Upvotes: 1

Related Questions