简体   繁体   English

如何从模型的数组属性中的对象属性中查找文档

[英]How to find document from object property in array property in model

I have two models: 我有两个模型:

User: 用户:

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

Company: 公司:

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

1. I want to find the user with permistion = 1 in Company. 1.我想在公司中找到permistion = 1的用户。

2. I want to find the user and result user: {name, company, permistionCompany} 2.我想找到用户和结果用户: {name, company, permistionCompany}

I have alrealy fix this problem. 我已经解决了这个问题。 The contruction of my model is so bad and I fix my model: 我的模型的构造太糟糕了,我修复了模型:

User: 用户:

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

Company: 公司:

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

And when I want to find user in this company and permistion = 1, I just use: 当我想在该公司中找到用户并且permistion = 1时,我只使用:

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

1) Two ways you can query inside an array. 1)可以在数组内部查询的两种方法。 You can use $elemMatch ( https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ ) or, given the structure of the schema, you can just do: 您可以使用$ elemMatch( https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ ),或者,在给出架构的结构的情况下,您可以执行以下操作:

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

2) Not quite understanding the question, but going to assume you want to get the information from your 'Users' collection given the query above. 2)不太了解这个问题,但是假设您希望从上述查询中从“用户”集合中获取信息。 If that's the case, you can do a .populate. 如果是这样,您可以执行.populate。 A good guide would be here: https://medium.com/@nicknauert/mongooses-model-populate-b844ae6d1ee7 一个好的指南将在这里: https : //medium.com/@nicknauert/mongooses-model-populate-b844ae6d1ee7

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM