Currently, my setup includes node v10, mongodb v4.2, and mongoose v5.9.
I have defined a UsersSchema:
const UsersSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
lowercase: true
},
...
A CompaniesSchema is also in place:
const CompaniesSchema = new Schema({
name: {
type: String,
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Users',
required: true
},
branches: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Branches'
}]
...
})
Additionally, there's a BranchesSchema structured as follows:
const BranchesSchema = new Schema({
name: {
type: String,
required: true,
},
company: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Companies',
required: true
}
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Users',
}]
})
The challenge I am facing involves querying all the companies owned by a user or the companies they are associated with through a branch. Here's what I attempted:
const id = 'MY_USER_ID'
const queryCompanies = await Companies.find({
$or: [{ user: id }, { "branches.users": [id] }],
});
The { user: id }
part of the query functions correctly. However, I am encountering issues when trying to retrieve companies based on the branches the user is associated with. Is it feasible to accomplish this task?