首页 > 解决方案 > 如何从模型中数组属性中的对象属性中查找文档

问题描述

我有两个模型:

用户:

{ 
    name: { type: String, required: true},
    company: { type: Schema.Types.ObjectId, ref: "Company" },
}

公司:

( 
    name: { type: String, required: true},
    users : [{
        user: {type: Schema.Types.ObjectId, ref: "User"},
        permistion: {type: Number, default: 0}
    }]
)

1.我想找permistion = 1公司里面的用户。

2.我要查找用户和结果用户:{name, company, permistionCompany}

我已经解决了这个问题。我的模型的构造非常糟糕,我修复了我的模型:

用户:

{ 
    name: { type: String, required: true},
    company: {
        id: { type: Schema.Types.ObjectId, ref: "Company" },
        userPermission: { type: Number, default: 0}
    },

公司:

( 
    name: { type: String, required: true},
    users : [{user: {type: Schema.Types.ObjectId, ref: "User"}],
)

当我想在这家公司找到用户并且权限 = 1 时,我只使用:

User.find({_id: userId, company.id: companyId, company.userPermistion: 1})

标签: javascriptmongoose

解决方案


1)您可以通过两种方式在数组内部进行查询。您可以使用 $elemMatch (https://docs.mongodb.com/manual/reference/operator/query/elemMatch/),或者,给定架构的结构,您可以这样做:

Company.find({"users.permistion": 1}, (error, docs) => {
  console.log(docs)  
})

2) 不太理解这个问题,但假设您想从给定上述查询的“用户”集合中获取信息。如果是这种情况,您可以执行 .populate。一个很好的指南会在这里:https ://medium.com/@nicknauert/mongooses-model-populate-b844ae6d1ee7

Company.find({"users.permistion": 1}).populate("users.user", (error, docs) => {
    console.log(docs)  
})

推荐阅读