Question

On mongoose there is a nice option to remove some fields from queries by default using the select: false option.

For Example:

var FileSchema = new Schema({
  filename: String,
  filesize: Number,
  base64Content: {type: String, select:false}
});

[...]

FileModel.find({}, function(err, docs) {
  // docs will give me an array of files without theirs content
});

Now, how can I use the same option to a field of subdocuments array?

(ie. in the following example, set select: false to the comments field)

var PostSchema = new Schema({
  user: ObjectId,
  content: String,
  createdAt: Date,
  comments: [{
    user: ObjectId,
    content: String,
    createdAt: Date
  }]
});

[...]

FileModel.find({}, function(err, docs) {
  // docs will give me an array of files without theirs content
});
Was it helpful?

Solution

Try creating a CommentSchema first,

var CommentSchema = new Schema({
  user: ObjectId,
  content: String
  //whatever else
});

and then in your PostSchema specify

comments: { type: [CommentSchema], select:false}

OTHER TIPS

Well you could do this:

comments: { type: Array, default: [], select: false }

But you would be losing the declared structure underneath, otherwise what is really wrong with:

comments: [{
    user: { type: ObjectId, select: false },
    content: { type: String, select: false }
    createdAt: { type: Date, select: false }
}]

Which may seem a bit terse, but likely someone thought it was sensible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top