0

I have read some solutions regarding this in stack overflow, but none suits my situation.

My mongo db collection _id is a composite key as shown below,

Mongo db Application Collection

{
"_id" : {
    "appId" : 1,
    "name" : "my app"
},
"dataLoaded" : true,
"__v" : 0
}

my code (gives empty result)

app.get('/api/application',function(req,res){
    Application.findOne({"_id" : req.query._id},function(err,application){
        if(err){
            res.status(500).send(err);
        }else{
            if(application){
                console.log("entered")
                res.status(200).send(application);
            }else{
                res.status(404).send(err);
            }

        }
    })
});

my code (gives a document as result)

app.get('/api/application',function(req,res){
    Application.findOne({"_id" : {"appId" : 1,"name" : "my app"}},function(err,application){
        if(err){
            res.status(500).send(err);
        }else{
            if(application){
                console.log("entered")
                res.status(200).send(application);
            }else{
                res.status(404).send(err);
            }

        }
    })
});

where as when my console.log(req.query._id) results {"appId" : 1,"name" : "my app"}

I can't understand what mistake I made. When _id is not a composite key then everything works fine.

Thanks in advance !!

Krishna Kiriti
  • 83
  • 2
  • 10
  • how does `req.query._id` resolves to object when it should be a string? How is the API called? Plz share the URL – sidgate Oct 30 '17 at 07:01
  • @sidgate this is how I called $http.get('/api/application',{params:{"_id":appDb._id}}), think your comment gave me required explanation. so it is a string then. I am newbie to this. Thanks a lot. – Krishna Kiriti Oct 30 '17 at 07:09
  • Even converting a string to an object, you are still doing it wrong. See [How to query nested objects?](https://stackoverflow.com/questions/16002659/how-to-query-nested-objects). Don't ever attempt to match against an "object", even if you think you are sure of the keys. Instead use "dot notation" to the inner paths of the properties, This makes sure the nested properties are matched "in any order". – Neil Lunn Oct 30 '17 at 07:17

1 Answers1

0

as sidgate suggested in comments, it is a string and can't be resolved as object. Passing the values of composite key as individual parameters is the only way.

Krishna Kiriti
  • 83
  • 2
  • 10