在mongoose中将select:false设置为子文档数组

Mos*_*tov 3 schema mongoose mongodb node.js subdocument

在mongoose上,有一个很好的选择,默认情况下使用该select: false选项从查询中删除一些字段.

例如:

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
});
Run Code Online (Sandbox Code Playgroud)

现在,我如何在子文档数组的字段中使用相同的选项?

(即在以下示例中,设置select: falsecomments字段)

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
});
Run Code Online (Sandbox Code Playgroud)

Mat*_*Kim 6

首先尝试创建CommentSchema,

var CommentSchema = new Schema({
  user: ObjectId,
  content: String
  //whatever else
});
Run Code Online (Sandbox Code Playgroud)

然后在你的PostSchema中指定

comments: { type: [CommentSchema], select:false}
Run Code Online (Sandbox Code Playgroud)