【问题标题】:Query multiple collections Nodejs查询多个集合Nodejs
【发布时间】:2019-12-28 04:41:03
【问题描述】:

您好,我正在尝试加入这些集合,我想获取所有“活动”属性等于 false 的用户。我不知道如何获取此查询。有我的架构:

用户架构

const mongoose = require('mongoose');
    const Schema = mongoose.Schema;

    const UserSchema = new Schema({
        name: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true
        },
        password: {
            type: String,
            required: true
        },
        type: {
            type: String,
            required: true
        },
        active:{
            type:Boolean
        }
    });

    module.exports = mongoose.model('users', UserSchema);

公司架构:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

        const CompanySchema = new Schema({
            userId: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'users'
            },
            companies: [{
                name: {
                    type:String
                },
                country:{
                    type:String
                }
            }
            ]
        });

        module.exports = Company = mongoose.model('company', CompanySchema);

注意:并非所有用户的公司都只有“客户”类型,我想同时获得“客户”和“雇员”

【问题讨论】:

  • 你能举一个你的两个集合的例子吗?输出如何?
  • 看起来您正在构建一个完整的关系应用程序。您可能需要一个关系数据库。

标签: node.js mongodb mongoose


【解决方案1】:

您可能希望重构架构以更好地适应您可用的数据类型。

例如:

用户架构:

const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    type: {
        type: String,
        required: true
    },
    active:{
        type:Boolean
    },
    companies: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'company'
    }]        
});

和公司架构:

const CompanySchema = new Schema({
    name: {
        type:String
    },
    country:{
        type:String
    }
});

然后获取所有活跃用户的列表,并自动为这些用户填充任何公司数据(假设您的用户模型称为 UserModel)

UserModel.find({ active: false }).populate('companies').exec();

如果您因任何原因无法编辑数据结构,则可以执行类似以下的查询:

CompanyModel.aggregate([
    { $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user' } },
    { $match: { '$user.active': false } }
]).exec()

这将对 UserId 字段执行聚合查找,然后仅匹配 active 属性设置为 false 的字段。

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 2014-08-09
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    相关资源
    最近更新 更多