2016-12-01 42 views
-1

我有模式:如何從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

回答

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

如果你想用默認隱藏字段:

{ 
    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://stackoverflow.com/questions/14040562/how-to-search-in-array-of-object-in-mongodb – alfredopacino

+0

elemMatch - 搜索陣列,這對我沒有幫助。 我需要搜索用戶,誰不在我的黑名單 – Jackson

相關問題