1

everyone hoping to all are fine. I'm new to node.js and mongodb and i'm having trouble passing in variables to a mongoose model query.

When I pass two arguments, its result is empty and however the record exists.

Retrieving data from MongoDB Image

Sending Get Request through Postman

GET Route: /data/:vehicle_no/:drive_id

URL: http://localhost/api/data/ZXC-1123/drive_234

Route Code:

var reg_no = req.params.vehicle_no;
drive_id: req.params.drive_id;
vehicle.find({
        ID: reg_no,
        Trip_Details: {
            FileName: drive_id
        }
    }, function(err, result) {
        if(err) {
            res.json(err);
        } else if(result.length > 0) {
            res.json("Drive id Found");
        } else {
            res.json("Drive id not Found");
        }
    })

Result: Drive id not found

However Expected Result must be: Drive id found

In the above code: Trip_Details is the objects array having file_name, _id, TripData.

And If I pass only one argument like vehicle.find({ ID: reg_no } then result found.

Kindly help, Thanks in Advance

  • you should use `"Trip_Details.FileName": drive_id` instead of `"Trip_Details:{FileName: drive_id}` so try it `vehicle.find({ID: reg_no, "Trip_Details.FileName": drive_id}, function(err, result){//..})` – Shaishab Roy Oct 26 '17 at 11:48
  • Thanks @ShaishabRoy , this worked +1 – user6542251 Oct 26 '17 at 12:13

1 Answers1

-1

To query based on two parameters, you can also use $and for better readability. The place where you went wrong is in writing query, second parameter should be written as :

vehicle.find({
ID: reg_no,
Trip_Details.FileName: drive_id
}

Your implementation using $and will be as follows:-

vehicle.find({
    $and: [
    {ID: reg_no},
    {Trip_Details.FileName: drive_id
    }]
}, function(err, result) {
    if(err) {
        res.json(err);
    } else if(result.length > 0) {
        res.json("Drive id Found");
    } else {
        res.json("Drive id not Found");
    }
})

For more information refer Mongoose Docs

Sriram J
  • 174
  • 1
  • 1
  • 9
  • From the manual, [Query Documents](https://docs.mongodb.com/manual/tutorial/query-documents/) and specifically [Specify AND Conditions](https://docs.mongodb.com/manual/tutorial/query-documents/#specify-and-conditions) *"The following example retrieves all documents in the inventory collection where the status equals "A" **and** qty is less than ($lt) 30: `db.inventory.find( { status: "A", qty: { $lt: 30 } } )`*. So like anyone who actually used the product and didn't just "google", you find out pretty quickly that the two are exactly the same. `$and` does not add anything new here. – Neil Lunn Oct 26 '17 at 12:04