Tuesday 6 June 2017

Seach inside array mongoose

I want to perform a query where i can search in all field even in array for example to get all projects that have type email here is my json but right now i can only search name and description i can't search inside array of items

here is my code

router.get('/search', function(req,res) {
var query = req.query;
for(p in query) {
  // added this to search so search works also with contains not just exact word
  query[p] = { "$regex": query[p], "$options": "i" }
}

Projects
.find(query)
.populate([
    {
    path: 'items.email',
    model: "Email",
  },{
    path: 'items.note',
    model: "Note",
  } , {
    path: 'items.image',
    model: "Image"
  }
]).where(query).exec(function(err,projects) {
    if(err) {
      console.log(err);
      res.json({"message":"could not find projects","status":false});
    }
    res.json(projects);
});

})

and this is my json

[{
"_id": "5935b558f586da1a94eb44fc",
"name": "First Project",
"description": "this is first project",
"items": [
  {
    "email": {
      "_id": "5935b558f586da1a94eb44f9",
      "text": "hi how are u",
      "subject": "hello",
      "email": "jhon_doe@gmail.com",
      "type": "email"
    },
    "note": {
      "_id": "5935b558f586da1a94eb44fb",
      "text": "hello I'm just a note",
      "type": "note"
    },
    "image": {
      "_id": "5935b558f586da1a94eb44fa",
      "url": "www.google.com/image",
      "type": "note"
    },
    "_id": "5935b558f586da1a94eb44fe"
  },
  {
    "email": {
      "_id": "5935b558f586da1a94eb44f9",
      "text": "hi how are u",
      "subject": "hello",
      "email": "jhon_doe@gmail.com",
      "type": "email"
    },
    "note": {
      "_id": "5935b558f586da1a94eb44fb",
      "text": "hello I'm just a note",
      "type": "note"
    },
    "_id": "5935b558f586da1a94eb44ff"
  }
],
"childProjects": [],
"createdAt": "2017-06-05T19:47:36.064Z"
} ]



via Kastriot Dreshaj

No comments:

Post a Comment