Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose select fields (nested)

I am trying to use the select operator in mongoose to select certain fields for the following object:

{
    "_id" : ObjectId("5249bb97a5de48bda3000003"),
    "id": 1,
    "geometry" : {
        "coordinates" : [
            1,
            1
        ],
        "type" : "Point"
    },
    "properties" : {
        "TYPE" : "Some Type",
            "TIMESTAMP": ......
    },
    "type" : "Feature"
}

I would like to mongo to return only the 'properties.TYPE' and properties.TIMESTAMP fields. I can do this in mongo with the following query:

db.features.find({id: 1}, {'properties.TYPE': 1, 'properties.TIMESTAMP': 1})

I am trying to use the select statement in mongoose to do the same thing: var fields = { properties: { OBJECTID: 1, TIMESTAMP: 1 } } var query = Feature.find({id: 1}).select(fields);

Mongo throws an error when trying to do that so I am not sure mongoose is formatting a nested fields object correctly.

Is this the proper way to do this?

like image 787
lostintranslation Avatar asked Oct 01 '13 15:10

lostintranslation


1 Answers

You can use the same dot notation style in the select object with Mongoose as you do in your find example:

var fields = { 'properties.OBJECTID': 1, 'properties.TIMESTAMP': 1 };
var query = Feature.find({id: 1}).select(fields);

You can also use a Mongoose style selection string:

var query = Feature.find({id: 1})
    .select('properties.OBJECTID properties.TIMESTAMP');
like image 146
JohnnyHK Avatar answered Oct 24 '22 08:10

JohnnyHK