我有一组文件,可以围绕它们设置各种READ隐私设置:
我很遗憾如何在MongoDB中有效地实现这种模式,并希望深入了解实现此模式的最佳实践。
答案 0 :(得分:0)
我们已经完成了多个具有多个访问级别和mongoose的项目,这是迄今为止我们最喜欢的方法:
var ACCESS_MODES = 'public followers private explicit'.split(' ');
var projectSchema = new Schema({
access: { type: String, enum: ACCESS_MODES, required: true, default: 'public' },
owner: { type: Schema.Types.ObjectId, ref: 'User' }]
});
然后我们通常在架构上实现一些自定义访问方法,例如:
projectSchema.statics.getByIdFor = function(user, id, done) {
this.findOne({ _id: id }).populate('owner').exec(onFound);
function onFound(err, project) {
// now check 'user' against the project's access method:
if (project.access === 'public') return done(undefined, project);
if (project.access === 'private') {
// ...etc, handle the logic for access at different levels
}
// finally, they didn't get access
done(new Error('no permission to access this project'));
}
};
所以你现在可以做这样的事情并且知道它是安全的:
ProjectModel.findByIdFor(loggedinUser, req.params.projectId, onFound);
要查找用户有权访问的所有项目:
projectSchema.statics.getForUser = function(user, done) {
var accessible = [];
this.find({ access: 'public' }).exec(onPublic);
this.find({ access: 'followers' }).populate('owner').exec(onFollowers);
this.find({ access: 'private', owner: user }).exec(onPrivate);
this.find({ access: 'explicit' }).populate('owner').exec(onExplicit);
// add onPublic/Followers/Private/Explicit to accessible where user is in the correct list
};
答案 1 :(得分:0)
由于你没有指定你正在使用的驱动程序(虽然标记了Javascript,所以也许你正在使用mongoose?)我将尝试使用伪代码/结构来回答这个问题。
我认为你的document
收藏品看起来像这样:
{
_id,
title,
owner, //ref to User collection?
access, //'public', 'followers' etc...
permissions[]
}
Permission
看起来像:
{
// one or the other
user_id
group_id
}
现在,棘手的部分是生成一个可供给定用户查看的文档列表 接近这个
function findDocumentsViewableByUser(userID){
var followedBy = //populate a list of userIDs that FOLLOW the passed in userID
var groupIDs = //populate a list of groupIDs this user is a member of
// all documents where access = 'public'
// all documents where access = 'followers' AND owner_id is in followedBy
// all documents where access = 'custom'
// and permissions.user_id = userID OR groupIDs contains permissions.groupID
}
根据用户和组类型文档的结构,上述findDocumentsViewableByUser中的查询将大大减少。
您也可能最好使用聚合框架。