在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
});
现在,我如何在子文档数组的字段中使用相同的选项?
(即在以下示例中,将select: false
设置为comments
字段)
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
});
答案 0 :(得分:6)
首先尝试创建CommentSchema,
var CommentSchema = new Schema({
user: ObjectId,
content: String
//whatever else
});
然后在PostSchema中指定
comments: { type: [CommentSchema], select:false}
答案 1 :(得分:0)
嗯,你可以这样做:
comments: { type: Array, default: [], select: false }
但是你会丢失下面声明的结构,否则会出现什么问题:
comments: [{
user: { type: ObjectId, select: false },
content: { type: String, select: false }
createdAt: { type: Date, select: false }
}]
这可能看起来有点简洁,但可能有人认为这是明智的。