Tuesday 23 May 2017

Find document by filtering sub-document Mongoose

I'm currently using Express and I'd like to create a route like this :

router.get('/actionsFiltered/:company/:user/:location',function(req,res,next){
  var query=Action.find({
    company:req.company._id,
    inCharge:req.user._id,
    'event.location':req.location._id,
  })
  .populate({
    path:'event',
    populate:[{path:'eventLocation'},{path:'anomaly'}],
  })...

My Action knows an Event by having an attribute 'event' referring to a Mongo ObjectID. My Event object have an attribute 'location', referring to a Mongo ObjectID too. I want to get the actions only if the parameter location match the location id owns by the event, itself owns by the action.

Here's an action :

{
    "_id" : ObjectId("591ecadd97d6f32bf0c6f3e7"),
    "company" : ObjectId("58eceb1d2a59fa1c5c4dfc9d"),
    "event" : ObjectId("591174b9ce02550140214bd3"),
}

Here's an event :

{
    "_id" : ObjectId("591174b9ce02550140214bd3"),
    "location" : ObjectId("586e9559b38f2a101caa77fc"),
}

And finally a location :

{
    "_id" : ObjectId("586e9559b38f2a101caa77fc"),
    "name" : "Wsh",
}

'event.location':req.location._id doesn't work but I don't know how to do the request. I could add the location field directly in the Action object but I don't want to if possible.



via Steak

No comments:

Post a Comment