Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set select: false to subdocuments array at mongoose

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
});
like image 447
Moshe Simantov Avatar asked Jun 22 '26 20:06

Moshe Simantov


1 Answers

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}
like image 180
Matt Kim Avatar answered Jun 25 '26 13:06

Matt Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!