nestjs mongoose关联查询


nestjs,mongoose关联查询网上搜不到了,查看了nest/mongoose.d.ts文件,分享一波

user.model.ts

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"
import { Document, Types } from 'mongoose';
import { ApiProperty } from '@nestjs/swagger'


    @Prop({ type: Types.ObjectId, ref: 'Role', default: null })//一个角色
    @ApiProperty({
        description: '角色id',
    })
    role: any;

    @Prop({ type: Types.ObjectId, ref: 'Deptbase', default: null })//一个部门
    @ApiProperty({
        description: '部门id',
    })
    dept: any;

role.model.ts

   

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"
import { Document, Types } from 'mongoose';
import { ApiProperty } from '@nestjs/swagger'

    @Prop({ type: [Types.ObjectId], default: [], ref: "Menu" })//多个权限
    @ApiProperty({
        description: '权限id',
    })
    authority: any[];

menu.model.ts:menu基本菜单信息,在此省略

------查询方法--------

1.查询角色和部门

     this.userModel.paginate(queryParams, {
            populate: [{
                path: 'role', select: '_id name', match: { "isDelete": false 
         }
            },
            {
                path: 'dept', select: '_id name code'
            }],
            select: '_id uid name status role dept creator createdAt',//显示字段,不懂查mongoose官网populate
            page: page > 0 ? page : 1,
            limit: size > 0 ? size : 20,
            sort: '-createdAt'
        })
path中的role,dept字段,user.model中有定义

2.查角色拥有的权限

this.roleModel.findOne({ _id: Types.ObjectId(roleId) }, { _id: 1, authority: 1 }).populate({
            path: 'authority',//authority在role.model.ts中定义
            select: "-creator -createTime -createdAt -updatedAt -opreator -isDelete",//加-为不显示字段
            match: {
                "isDelete": false,
                "appId": Types.ObjectId(appId)
            },
            options: {
                $sort: {
                    createdAt: 1
                }
            }
        })