the_islander
the_islander

Reputation: 207

Mongodb multiple conditions

New to MongoDB and express interactions. I'm trying to query the database based on URL parameters, essentially I want to grab URL parameters then add them to an object if they exist to use when querying the database. I set up my express path and understand that the find() method accepts an object, when I hard code the key-value pair like below I get the correct data but when I set an object called filter with the same key-value pairs as the hard-coded example and uncomment filter and comment state and type then pass it to the find method I get an empty array. Whats the reason for this and what's the best way to achieve this?

    app.get('/query', function (req, res) {

    var filter = {

        state: "florida",
        type: "red"
    }

    db.collection('tickets').find({ 
            //filter
            state:"florida",
            type:"red"

        })
        .toArray(function (err, documents) {
            // Here is where we decide what to do with the query results
            if (err) 
                throw err
            res.send(documents)

        })
});

Upvotes: 0

Views: 595

Answers (1)

Shimon Brandsdorfer
Shimon Brandsdorfer

Reputation: 1723

The find method accepts a query object as the first parameter, the query object is your filter object yourself. therefore, you should do it like this:

db.collection('tickets').find(filter)
            .toArray(function (err, documents) {
                // Here is where we decide what to do with the query results
                if (err) 
                    throw err
                res.send(documents)

            })

Upvotes: 2

Related Questions