在对象数组内的猫鼬查询数组

问题描述 投票:1回答:1

所以我正在使用节点v10,mongodb v4.2和mongoose v5.9。

我有一个UsersSchema:

const UsersSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
        lowercase: true
    },
 ...

A CompaniesSchema:

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'
    }]
    ...

})

和一个BranchesSchema:

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',
    }]
})

我需要查询用户拥有的所有公司,或者查询他已添加到分支机构的公司。我试图这样做:

const id = 'MY_USER_ID'
const queryCompanies = await Companies.find({
  $or: [{ user: id }, { "branches.users": [id] }],
});

{ user: id }部分起作用。我很难根据他所在的分支机构来查询他所在的公司。那有可能吗?

javascript mongodb mongoose mongodb-query
1个回答
1
投票

使用当前模式设置,您有2个选项:

  1. 分为2个通话:
const id = 'MY_USER_ID';
let companyIds = await Branches.distinct("company", {users: id});
const queryCompanies = await Companies.find({
    $or: [{ user: id }, { _id: {$in: companyIds} }],
});

  1. 使用$lookup
const id = 'MY_USER_ID';
const queryCompanies = await Companies.aggregate([
    {
        $lookup: {
            from: "branches",
            let: {companyId: "$_id", userId: id},
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    $eq: ["$$companyId", "$company"]
                                },
                                {
                                    $setIsSubset: [["$$userId"], "$users"]
                                }
                            ]
                        }
                    }      
                }
            ],
            as: "branches"
        }
    },
    {
        $match: {
            $or: [
                {
                    user: id
                },
                {
                    "branches.0": {$exists: true}
                }
            ]
        }
    }
]);

我个人推荐选项1,因为Mongo不喜欢查找,尤其是在这里您必须对整个集合进行查找。

© www.soinside.com 2019 - 2024. All rights reserved.