问题
I have to make a page for entering some data about people on specific regions. Each user will have prvileges on a specific region.
So I will make two collections into a DB. One for the users and one for the regions.
The users will have access only to one region (or in some cases to more) and specific acceses, like read or write, or read&write, and so on.
How can I model my schema so I can add more regions?
That's how I did it:
var mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
let userSchema = new mongoose.Schema({
username:
{type: String,
unique: true
},
password: String,
privileges:
{
regiune: [Number],
read: [Number],
write: [Number],
edit: [Number]
}
});
userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", userSchema);
but I don't know how I should edit this model so it can have multiple regions with different privileges. For regular users they might have one region with read, write and edit, let's say. But if I want another user to have access to region x with read, write privileges and region y with write privileges I won't be able to do it using this schema.
So how should I edit this? (also, I'm a beginner in DBs so if there is another better way to set privileges please let me know)
Thanks!
回答1:
Actually, since the privileges field belongs to each user, you can easily have multiple regions with different privileges
Turn privileges into an array and each particular permission into a number and you have it!
privileges:
[{
regiune: Number,
read: Number,
write: Number,
edit: Number
}]
An array of objects is the idiomatic way to model dependent objects in Mongo. People generally recommend not having an unbounded array as subdocument, but I bet your list of regions is relatively finite.
You will probably want to introduce some mechanism for ensuring that you have unique regiunes in the array. Mongo 4.10 introduced a plugin for this: https://www.npmjs.com/package/mongoose-unique-array that you can use like this:
privileges:
[{
regiune: { type: Number, unique: true },
read: Number,
write: Number,
edit: Number
}]
If you wanted to access your permissions as an object, by key: region1, region3, etc. Then you might declare privileges as a mixed type, meaning it can be any arbitrary json structure (but you lose type information). Or you might make it a separate model, collection with a back ref to the user object. The user object could also have a list of references to this new model (but it would again be an array and not an object).
来源:https://stackoverflow.com/questions/53574308/making-a-mongodb-userschema-with-specific-privileges-on-each-region