我有架构:
{
name: String,
surname: String,
note: String,
someField: String,
secondSomeField: String
blackList: [{
userId: mongoose.Types.ObjectId,
reason: String
}]
}
我需要选择包含所有字段的文档,但在blackList字段中我需要只选择userId。示例我想要的:
{
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 :(得分:1)
如果您想默认隐藏字段:
{
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
})
未经测试,但他们应该兼顾。
答案 1 :(得分:0)
Schema.aggregate( {$match: {_id: mongoose.Types.ObjectId(myCustomId)} }, {$project: {blackList: "$blackList.userId", name: true, surname: true, someField: true}} ).exec(fn)