大家好,我在从数据库获取用户允许的字段时遇到问题。 所以我的架构是:
var profileSchema = mongoose.Schema({
authId: {type: Schema.Types.ObjectId, ref: 'Auth'},
fname: String,
lname: String,
am: Number,
email: String,
location: String,
languages: [String],
birth_date: {
type: Date,
default: Date.now
},
reg_date: {
type: Date,
default: Date.now
},
last_log: {
type: Date,
default: Date.now
},
permissions: {
location: {type: Boolean,Default:true},
birth_date: {type: Boolean,Default:true},
email: {type: Boolean,Default:true},
am: {type: Boolean,Default:true},
subjects: {type: Boolean,Default:true},
files: {type: Boolean,Default:true},
posts: {type: Boolean,Default:true}
},
ip: String,
subjects: [{type: Schema.Types.ObjectId, ref: 'Subject'}],
files: [{type: Schema.Types.ObjectId, ref: 'FileIndex'}],
posts: [{type: Schema.Types.ObjectId, ref: 'Post'}],
notifications: [{type: Schema.Types.ObjectId, ref: 'Notifications'}]
});
我试图只获得权限字段中的字段为true,这意味着它是允许的。所以我正在运行以下查询:
database.Profile.findOne({_id: req.params.id}).exec(function (err, profile) {
console.log(profile);
res.send(profile);
});
如何仅选择允许的字段?
答案 0 :(得分:1)
试试这个,它可能会得到你想要的东西:
database.Profile.findOne({_id: req.params.id},{location:$.permissions.location , birth_date:$.permissions.birth_date, email:$.permissions.email, am:$.permissions.am, subjects:$.permissions.subjects, files:$.permissions.files, posts:$.permissions.posts}).exec(function (err, profile) {
console.log(profile);
res.send(profile);
});
答案 1 :(得分:1)
您可以使用链接的 lean()
方法执行查询,因为启用了精益选项的查询返回的文档是纯JavaScript对象,而不是MongooseDocuments并操纵返回的对象删除权限对象字段确定的密钥:
Object.filter = function( obj, predicate) {
var result = {}, key;
for (key in obj) {
if (obj.hasOwnProperty(key) && !predicate(obj[key])) {
result[key] = obj[key];
}
}
return result;
};
database.Profile.findOne({_id: req.params.id}).lean().exec(function (err, doc) {
if (err) return handleError(err);
console.log(doc);
console.log(doc.permissions);
var filtered = Object.filter(doc.permissions,
function (key){ return doc.permissions[key]; }
);
console.log(filtered);
res.send(filtered);
});
使用Mongoose的投影 select()
方法的另一种方法是进行两次查询;第一个将返回整个文档,下一个将查询同一文档,但根据权限对象字段投影字段:
以下显示了这一点:
database.Profile.findOne({_id: req.params.id}).lean().exec(function (err, doc) {
console.log(doc);
console.log(doc.permissions);
var projection = Object.keys(doc.permissions)
.filter(function (key){ return doc.permissions[key]; })
.join(' ');
console.log(projection);
database.Profile.findOne({_id: req.params.id})
.select(projection)
.exec(function (err, profile) {
if (err) return handleError(err);
res.send(profile);
});
});