如何返回与隐私值相关的特定对象值?
我有这个mongoose模型:
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} })
假设用户将displayLastName
abd displayLastName
的值设置为false
。
然后,我有一个简单的GET请求,返回一个json对象与所有用户的细节。 我如何查询mongo只返回隐私对象中的true
的字段? 如果displayfirstName
为true,则返回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 } })
我如何有条件地检查地址和电话字段?
我能想到的唯一方法是通过一个具有$cond
expression式的$project
操作符的聚合pipe道,该expression式计算条件并根据所评估的逻辑返回其他两个expression式之一的值。
举例来说,运行下面的pipe道会给你一个显示所有字段的文档,但是它们的值取决于display subdocument字段的值。 如果它是真的,则返回实际值,否则返回空值:
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)); })
UPDATE
从注释中继续处理另一个问题,有条件地检查address
和phone
字段AND
并使用GET
参数中的id过滤集合,使用作为查询的$match
操作符运行pipe道,然后添加额外的信息字段有条件的显示在你的$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)); })