Oscar Yuandinata Oscar Yuandinata - 25 days ago 8
Node.js Question

how to exclude array type fields with mongoose

I have a schema like this:

var CitySchema = new Schema({
name: {type : String, required : true},
region: {type: Schema.Types.ObjectId, ref: 'Region', required : true},
images: [{type : Schema.Types.ObjectId, ref: 'Image', select: false}]
});


When I do query on the collection, the field images would still show up even when I put the
select: false
. How can I hide the field without using
.select('-images')
?

Answer

When you are putting select: false, you say to exclude values inside the images array. You need to put select: false for the images array itself.

Look at this stackoverflow post.


Applied to your case:

var CitySchema   = new Schema({
    name: {type : String, required : true},
    region: {type: Schema.Types.ObjectId, ref: 'Region', required : true},
    images: { 
      type: [{type : Schema.Types.ObjectId, ref: 'Image', select: false}],
      select: false, 
    },
});
Comments