简体   繁体   中英

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
});

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}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM