【问题标题】:In Mongoose I have User and Role schemas that have a one to many relationship. How to query if a particular User has the 'admin' role?在 Mongoose 中,我有具有一对多关系的用户和角色模式。如何查询特定用户是否具有“管理员”角色?
【发布时间】:2021-07-13 06:46:09
【问题描述】:

我的 Mongo DB 中有两个集合:用户和角色。一个用户可以有很多角色。使用猫鼬我想找出特定用户(基于他们的 id)是否具有管理员角色。如何执行该查询?在 SQL 中查找的一种方法是编写以下查询:

SELECT *
FROM Users
INNER JOIN Roles ON Users.id = Roles.userID
WHERE (Users.id = <some user id> AND Roles.name='admin')

但我看不到如何使用 Mongoose 完成等效查询。以下是我的 Mongoose 架构:

let RoleSchema = new Schema({
    name: String,
    owner: {
        type: Schema.Types.ObjectId,
        ref: "User"
    }
})
export let Role = mongoose.model("Role", RoleSchema)


let userSchema = new Schema({
    username: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    roles: [
        {
            type: Schema.Types.ObjectId,
            ref: "Role"
        }
    ]
})
export let User = mongoose.model("User", userSchema)

【问题讨论】:

    标签: mongodb mongoose mongodb-query one-to-many mongoose-populate


    【解决方案1】:

    阅读 - https://mongoosejs.com/docs/populate.html#query-conditions

    User.
      findById(id). // can also use find/findOne depending on your use-case
      populate({
        path: 'roles',
        match: { name: 'admin' }
      }).
      exec();
    

    这将获取nameadmin 的用户详细信息和角色。

    您可以检查user.roles 数组计数以获取用户是否具有管理员角色。

    【讨论】:

    • 谢谢!您的答案和随附的引用看起来很有希望我明天会运行代码,如果它有效,我会将您的代码标记为正确答案。顺便说一句,我希望 Mongoose 文档作者可以制作一个更好的索引——将用户引导到这些页面的索引是一个搜索“查询一对多关系”的索引。可取之处当然是 stackoverflow,它似乎越来越成为人们找到合适文档的索引。再次感谢您的回答!
    猜你喜欢
    • 2018-04-29
    • 2021-05-02
    • 2010-12-22
    • 2019-06-16
    • 1970-01-01
    • 2016-12-17
    • 2019-03-31
    • 2014-05-16
    相关资源
    最近更新 更多