9

I want the location field of my schema to be hidden by default. I added select: false property to it, but it is always returned when selecting documents...

var userSchema = new mongoose.Schema({

cellphone: {
  type: String,
  required: true,
  unique: true,
},

location: {
  'type': {
    type: String,
    required: true,
    enum: ['Point', 'LineString', 'Polygon'],
    default: 'Point'
   },
   coordinates: [Number],
   select: false, <-- here
   },
});

userSchema.index({location: '2dsphere'});

When calling :

User.find({ }, function(err, result){ console.log(result[0]); });

the output is :

 {  
    cellphone: '+33656565656',
    location: { type: 'Point', coordinates: [Object] } <-- Shouldn't
 }

EDIT : Explanation (thanks to @alexmac)

SchemaType select option must be applied to the field options not a type. In you example you've defined a complex type Location and added select option to a type.

Scaraux
  • 3,841
  • 4
  • 40
  • 80

1 Answers1

4

You should firstly create locationSchema and after that use schema type with select: false:

var locationSchema = new mongoose.Schema({
    'type': {
        type: String,
        required: true,
        enum: ['Point', 'LineString', 'Polygon'],
        default: 'Point'
       },
       coordinates: [Number]
    }
});

var userSchema = new mongoose.Schema({
    location: {
      type: locationSchema,
      select: false
    }
});
alexmac
  • 19,087
  • 7
  • 58
  • 69
  • We are close, coordinates aren't shown anymore, but the rest of location is : `"location": { "type": "Point" }` Note: I added select: false to location too. – Scaraux May 09 '16 at 12:49
  • Ok, I thought you want to hide only `coordinates` field, if you want to hide `location` completely, you should define it schema for it and use it as type. – alexmac May 09 '16 at 13:06
  • Can you just remove the bracket after `coordinates`, and replace the `;` after locationSchema by a `,`. Finally, could you just explain why select attribute doesn't direclty work within nested objects ? Why do we have to declare external schemas ? – Scaraux May 09 '16 at 13:13
  • SchemaType `select` option must be applied to the field options not a type. In you example you've defined a complex type `Location` and added `select` option to a type. – alexmac May 09 '16 at 13:28