我有这个猫鼬模型:
var user = new Schema({
email : {type: String},
firstName: {type: String},
lastName: {type: String},
username: {type:String},
password: {type:String},
privacy : {
displayEmail: {type: Boolean, default: true},
displayUsername: {type:Boolean: default: true},
displayfirstName: {type:Boolean: default: true},
displaylastName: {type:Boolean: default: true}
})
我们假设用户将displayEmail
abd displayLastName
的值设置为false
。
然后,我有一个简单的GET请求,它返回一个包含所有用户详细信息的json对象。如何查询mongo以仅返回隐私对象中具有true
的字段?如果displayfirstName
为真,则应返回firstName
值。
更新
var user = new Schema({
email : {type: String},
firstName : {type: String},
lastName : {type: String},
username : {type:String},
password : {type:String},
privacy : {
displayEmail : {type: Boolean, default: true},
displayUsername : {type:Boolean, default: true},
displayfirstName : {type:Boolean, default: true},
displaylastName : {type:Boolean, default: true},
displayAddress : {type: Boolean, default: true}, // new
displayPhone : {type: Boolean, default: true} // new
},
extraInfo : {
userAddress : {type:String}, // new
userPhone : {type: String} // new
}
})
我如何有条件地检查地址和电话字段?
答案 0 :(得分:1)
我能想到的唯一方法是通过一个聚合管道,该管道具有 $project
运算符,其 $cond
表达式可以评估条件并根据所评估的逻辑返回其他两个表达式之一的值。
User.aggregate([
{
"$project": {
"email": {
"$cond": ["$privacy.displayEmail", "$email", null]
},
"firstName": {
"$cond": ["$privacy.displayfirstName", "$firstName", null]
},
"lastName": {
"$cond": ["$privacy.displaylastName", "$lastName", null]
},
"username": {
"$cond": ["$privacy.displayUsername", "$username", null]
}
}
}
]).exec(function(err, users){
if (err) throw err;
console.log(JSON.stringify(users, null, 4));
})
根据评论中的其他问题,有条件地检查address
和phone
字段AND
是否使用GET
参数中的ID过滤集合,运行带有 $match
运算符的管道,该运算符充当查询,然后在 $project
中添加额外的信息字段条件显示:
var userId = mongoose.Schema.Types.ObjectId(req.parameter.userId);
User.aggregate([
{ "$match": { "_id": userId } },
{
"$project": {
"email": {
"$cond": ["$privacy.displayEmail", "$email", null]
},
"firstName": {
"$cond": ["$privacy.displayfirstName", "$firstName", null]
},
"lastName": {
"$cond": ["$privacy.displaylastName", "$lastName", null]
},
"username": {
"$cond": ["$privacy.displayUsername", "$username", null]
},
"userAddress": {
"$cond": ["$privacy.displayAddress", "$extraInfo.userAddress", null]
},
"userPhone": {
"$cond": ["$privacy.displayPhone", "$extraInfo.userPhone", null]
}
}
}
]).exec(function(err, users){
if (err) throw err;
console.log(JSON.stringify(users, null, 4));
})