36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { InjectModel } from '@nestjs/mongoose';
|
|
import { Types, Model } from 'mongoose';
|
|
import { User, UserDocument } from '@/models/user.model';
|
|
import { CreateUserInput } from './dto/create-user.input';
|
|
|
|
@Injectable()
|
|
export class UsersService {
|
|
|
|
constructor(
|
|
@InjectModel(User.name) private readonly userModel: Model<UserDocument>
|
|
) { }
|
|
|
|
async findAll(projection?: any): Promise<UserDocument[]> {
|
|
return this.userModel.find({}, projection, { lean: false }).populate({ path: 'person', select: projection?.person }).exec();
|
|
}
|
|
|
|
async findById(id: Types.ObjectId, projection?: any): Promise<UserDocument | null> {
|
|
return this.userModel.findById(id, projection, { lean: false }).populate({ path: 'person', select: projection?.person }).exec();
|
|
}
|
|
|
|
async create(input: CreateUserInput): Promise<UserDocument> {
|
|
const user = new this.userModel(input);
|
|
return user.save();
|
|
}
|
|
|
|
buildProjection(fields: Record<string, any>): any {
|
|
const projection: any = {};
|
|
for (const key in fields) {
|
|
if (key === 'person' && typeof fields[key] === 'object') { for (const subField of Object.keys(fields[key])) { projection[`person.${subField}`] = 1 } }
|
|
else { projection[key] = 1 }
|
|
}
|
|
return projection;
|
|
}
|
|
}
|