首页 > 解决方案 > 猫鼬过滤文档

问题描述

我正在使用 mongoose(规范化文档)学习 mongodb,并试图了解如何跨引用文档获取数据

const employeeSchema = new Schema({
    name: String,
    email: String,
});

const ContactSchema = new Schema({
    email: String,
    mobile: String,
    fax: String,
});

const DepartmentSchema = new Schema({
    contact: ContactSchema,
    title: String,
    director: {
        type: Schema.Types.ObjectId,
        ref: 'Employees',
    },
});

const ChannelSchema = new Schema({
    title: String,
});

const StudentSchema = new Schema({
    channel: {
        type: Schema.Types.ObjectId,
        ref: 'Channels',
    },
    department: {
        type: Schema.Types.ObjectId,
        ref: 'Departments',
    },
    name: {
        type: String,
    },
});

const Students = model('Students', StudentSchema);
const Departments = model('Departments', DepartmentSchema);
const Channels = model('Channels', ChannelSchema);
const Employees = model('Employees', employeeSchema);

如何在猫鼬中实现如下查询

Students.find({ name: 'studentName' }); //Ok
Students.find({ channel: { name: 'channelName' } });
Students.find({ department: { director: { name: 'directorName' } } });
Students.find({ department: { contact: { email: 'emailDirector' } } });

第一行按预期工作

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


推荐阅读