Nodejs:多个MongoDB中的一对多
我正在Mongo开发我的第一个数据库。 我使用Mongoose来创build模型。 我想实现一对多的多重关系。 有三种模式:用户,组和angular色模型。 用户可以属于多个组,并且可以在同一组中具有多个angular色。 例如,John属于组1和2.组1中的Juan是pipe理员,组2是pipe理员和超级用户。 下面我显示关系模式:
模式关系
我创build了以下模型:
的usermodel
const userSchema = new Schema({ username: {type: String, unique: true}, first_name: String, middle_name: String, first_surname: String, second_surname: String, email: String, password: String }, { timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'} }); const UserModel = mongoose.model('user', userSchema);
好榜样
const roleSchema = new Schema({ name: {type: String, unique: true}, code: {type: String, unique: true}, description: String }, { timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'} }); const RoleModel=mongoose.model('role', roleSchema);
GroupModel
const groupSchema = new Schema({ name: {type: String, unique: true} }, { timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'} }); const GroupSchema = mongoose.model('group', groupSchema);
GroupUserRoleModel
const groupuserroleSchema = new Schema({ role: {type: Schema.Types.ObjectID, ref: 'role'}, user: {type: Schema.Types.ObjectID, ref: 'user'}, group: {type: Schema.Types.ObjectID, ref: 'group'} }); const GroupUserRoleModel = mongoose.model('group_user_role', groupuserroleSchema);
我的问题是:
- 这确定的实现?
- 当我想创build一个GroupUserRole文档时,它是如何工作的?
我已经看到有关方法在mongoose( 填充 )填充的信息,但只有两个模型之间有一个关系船感谢您的帮助。
模型的build立
好的,这里的问题是,你想创build一个“关系型数据库”,比如使用mongodb,还是要模拟一个“NoSQL”types的数据库?
我看到你正在做什么,再现关系模式。 这是一个常见的错误,这里是解释为什么你应该避免这种情况。 使用mongodb,有一些新的概念,你应该知道像一个新的关系(一对一些,多到一些),其中some
代表一个小组的文件(我们可以称之为子文档)的组/列表。 mongodb的主要好处是尽可能减less收集。
如果你想要解释一下子文件在mongoose中的工作方式,请看http://mongoosejs.com/docs/subdocs.html
为了解决你的问题,我想(如果你没有那么多的团体和angular色,我想),你应该这样做:
的usermodel
const roleSchema = new Schema({ name: {type: String, unique: true}, code: {type: String, unique: true}, description: String }, { timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'} }); const groupSchema = new Schema({ name: {type: String, unique: true} }, { timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'} }); const userSchema = new Schema({ username: {type: String, unique: true}, first_name: String, middle_name: String, first_surname: String, second_surname: String, email: String, password: String, roles: [roleSchema], groups: [groupSchema] }, { timestamps: {createdAt: 'created_at', updatedAt: 'updated_at', deleteAt: 'delete_at'} }); const UserModel = mongoose.model('user', userSchema);
现在你有一个集合“用户”,你可以pipe理你的用户,他们的团体和他们的angular色。
用法
var user = new UserModel({ name: "Odonno", groups: [{ name: 'Admin' }, { name: 'User' }] }) user.save(callback);
一旦你有了你的模型,你可以很容易地设置组和angular色,然后将其保存在数据库中。