如何从Mongoose数组中的每个对象中只选择一个字段?

问题描述:

我有模式:如何从Mongoose数组中的每个对象中只选择一个字段?

{ 
    name: String, 
    surname: String, 
    note: String, 
    someField: String, 
    secondSomeField: String 
    blackList: [{ 
    userId: mongoose.Types.ObjectId, 
    reason: String 
    }] 
} 

我需要的所有字段选择文件,但在黑名单领域,我需要只选择用户ID。示例我想要的:

{ 
     name: "John", 
     surname: "Doe", 
     note: "bwrewer", 
     someField: "saddsa", 
     secondSomeField: "sadsd", 
     blackList: [58176fb7ff8d6518baf0c931, 58176fb7ff8d6518baf0c932, 58176fb7ff8d6518baf0c933, 58176fb7ff8d6518baf0c934] 
} 

我该如何做到这一点?当我做

Schema.find({_id: myCustomUserId}, function(err, user) { 
     //{blackList: [{userId: value}, {userId: value}]} 
     //but i need 
     //{blackList: [value, value, value]} 
}) 
+0

它的回答是: 'Schema.aggregate( {$比赛:{_id:mongoose.Types.ObjectId(myCustomId)}},{ $项目:{黑名单: “$ blackList.userId”,名称:true,surname:true,someField:true}}).exec(fn)' – Jackson

Schema.aggregate({$match: {_id: mongoose.Types.ObjectId(myCustomId)} }, {$project: {blackList: "$blackList.userId", name: true, surname: true, someField: true}}).exec(fn) 

如果你想用默认隐藏字段:

{ 
    name: String, 
    surname: String, 
    note: String, 
    someField: String, 
    secondSomeField: String 
    blackList: [{ 
    userId: mongoose.Types.ObjectId, 
    reason: {type:String, select:false} 
    }] 
} 

如果你只是想在该查询排除:

Schema 
    .find({_id: myCustomUserId}) 
    .select("-blackList.reason") 
    .exec(function (err, user) { 
     //your filtered results 
}) 

未经测试,但他们应该工作都。

+0

我didnot测试,但我测试了一个类似的查询,结果是:因为我会执行下一个查询:'Schema.find({_ id:{$ nin:arrayOfIds}})' – Jackson

+0

您可以保留第一个查询以这种方式并使用'$ elemMatch'编辑下一个查询。看到这个答案http://*.com/questions/14040562/how-to-search-in-array-of-object-in-mongodb – alfredopacino

+0

elemMatch - 搜索阵列,这对我没有帮助。 我需要搜索用户,谁不在我的黑名单 – Jackson