mongoose排除数组中的字段

我有这样的东西:

Schema Subdocument name: String data: Mixed Schema Stuff documents: [Subdocument] 

现在,在我的API中有两个端点,一个用于Subdocument ,另一个用于Stuff 。 当我想获得一个Subdocument我需要包含data字段,但是当我想要得到的Stuff ,我想显示这些子文档的名称,但我不想显示数据字段,因为是相当大的,它将不会被使用。

所以,为了保持清楚,数据不是私人的。 只是我不希望它从Stuff得到显示

我试着做:

 Stuff.findById(id) .populate("documents") .populate("-documents.data") 

但这是行不通的…我得到的Stuff与包含namedataSubdocument 。 当我调用populate("-documents.data") documents是一个数组,我想排除数组中的每个元素的data字段时,我觉得我错过了告诉mongoose。

编辑:对不起,我提供的架构是不适合我的情况。 在我的情况下,它不是embedded式的,而是一个参考,就像这样:

 Schema Subdocument name: String data: Mixed Schema Stuff documents: [{ type: Schema.Types.ObjectId, ref: 'Subdocument' }] 

假设subDocument没有embedded,并使用“ref”作为你说填充工作,但数据部分不包括在内:

 Stuff.findById(id).populate( { "path" : "documents", "select" : "-data" }) 

您的文档具有“embedded”模式,因此在此不使用填充,仅用于其他对象位于另一个集合中的“引用”模式。

幸运的是,“embedded式”使用投影有一个简单的方法:

 Stuff.findById(id,{ "documents.name": 1 },function(err,results) { }) 

像结果一样

 { "documents": [{ "name": "this" },{ "name": "that" }] } 

或者使用.aggregate()$map操作符:

 Stuff.aggregate( [ { "$match": { "_id": ObjectID(id) } }, { "$project": { "documents": { "$map": { "$input": "$documents", "as": "el", "in": "$$el.name" } } }} ],function(err,results) { } ) 

这只会变成一个“唯一”的名称“值”,这是不同的最后一种forms的数组。

 { "documents": ["this", "that"] } 

请注意,如果使用.aggregate() ,则需要正确地将ObjectId强制转换为自动生成的mongoose模式types在聚合stream水线阶段不起作用。