添加过滤器以获取mongoose中文档内部数组中的必需项

时间:2016-06-18 18:47:29

标签: mongodb mongoose

我有一次"旅行" mongoDB中的集合项

{
    "_id": "57658fdfa38f5708a8cb19e3",
    "routeName": "Sample Trip",
    "startTime": "13:00",
    "__v": 0,
    "creationDate": "2016-06-18T18:15:59.700Z",
    "routePoints": [
      {
        "creationDate": "2016-06-18T18:15:59.699Z",
        "_id": "57658fdfa38f5708a8cb19de",
        "address": "De Leon Middle School 4201 N 29th Ln, McAllen, TX 78504",
        "lng": 98.249278,
        "lat": 26.245306,
        "startTime": "13:00",
        "name": "Stop 1"
      },
      {
        "creationDate": "2016-06-18T18:15:59.699Z",
        "_id": "57658fdfa38f5708a8cb19df",
        "address": "Buddy Owens Blvd & N 29th St McAllen, TX 78504",
        "lng": 98.246389,
        "lat": 26.2485,
        "startTime": "13:05",
        "name": "Stop 2"
      },
      {
        "creationDate": "2016-06-18T18:15:59.699Z",
        "_id": "57658fdfa38f5708a8cb19e0",
        "address": "N 29th St & Wisteria Ave McAllen, TX 78504",
        "lng": 98.245861,
        "lat": 26.251472,
        "startTime": "13:10",
        "name": "Stop 3"
      },
      {
        "creationDate": "2016-06-18T18:15:59.699Z",
        "_id": "57658fdfa38f5708a8cb19e1",
        "address": "N 29th St & Zinnia Ave McAllen, TX 78504",
        "lng": 98.245639,
        "lat": 26.252833,
        "startTime": "13:15",
        "name": "Stop 4"
      },
      {
        "creationDate": "2016-06-18T18:15:59.700Z",
        "_id": "57658fdfa38f5708a8cb19e2",
        "address": "N 29th St & Bluebird Ave McAllen, TX 78504",
        "lng": 98.245417,
        "lat": 26.254194,
        "startTime": "13:20",
        "name": "Stop 5"
      }
    ]
  }

我正在使用

var tripFieldsRequired      = {details:0};


    Trip.find({_id: tripId}, tripFieldsRequired, function(err,data)
                {
                    if(err) 
                    {
                        response = {"error" : true, "invalidKey" : true, "message" : "No Driver found"};
                        res.json(response);
                    } 
                    else 
                    {
                        response = {"error" : false, "data" : data[0]};
                        res.json(response);
                    }
                });  

只获得我想要的那些领域。但是,内部数据定义为

routePoints   : { type : Array , "default" : [] },

现在我想从routePoints中只获得一些项目,主要是我想从路由点中删除"creationDate"id作为响应。

我将如何在上面的代码中添加这样的过滤器?

1 个答案:

答案 0 :(得分:1)

You can project over the nested fields using dot notation in quotes like this:

var tripFieldsRequired = {details:0, "routePoints._id":0, "routePoints.creationDate":0};

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#projection-on-embedded-documents-in-an-array