javascript - 如何从模型中数组属性中的对象属性中查找文档
问题描述
我有两个模型:
用户:
{
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})
解决方案
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)
})
推荐阅读
- sql - Intellisense 已刷新,但更新语句不适用于 SSMS 2017
- swift - ObjectIdentifier 与被破坏的对象重复
- c# - 如何访问另一个表单或类中的元素
- c# - 使用 C# 发出警报以在一天中的特定固定时间响铃
- php - 为什么注入 EntityManagerInterface 会返回无法序列化 PhpFilesAdapter 错误
- c# - 发送方法体运行时然后执行?
- python - 为什么我无法从 python 3 中的 django 模型导入对象?
- android - 安装插件媒体后,我的科尔多瓦应用程序卡住了
- docker - 在 Pivotal Cloud Foundry 中限制可运行的 Docker 映像
- c++ - 柯南和 gRPC:对各种“gpr_”符号的未定义引用