Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose select: false not working on location nested object

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.

like image 810
Scaraux Avatar asked May 09 '16 12:05

Scaraux


1 Answers

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
    }
});
like image 177
alexmac Avatar answered Oct 19 '22 19:10

alexmac