As a newcomer to Typescript and Nest.js, I'm feeling a bit lost in my project involving Nest, MongoDB with Mongoose, and Express.js. My main focus right now is on the User model:
import * as Mongoose from 'mongoose';
export const UserSchema = new Mongoose.Schema(
{
username: { type: String, required: true },
posts: { type: [Mongoose.SchemaTypes.ObjectId], ref: 'Post' },
favs: { type: [Mongoose.SchemaTypes.ObjectId], ref: 'Post' },
},
{
timestamps: true,
},
);
I'm building an API for a Twitter-like app where users can create posts and add them to their Favorites. While following tutorials, I've hit a roadblock when it comes to pushing a new favorite post to a user's list. Here's what the User controller looks like so far:
import {
Controller,
Get,
Req,
Res,
HttpStatus,
Put,
NotFoundException,
Param,
} from '@nestjs/common';
import { UserService } from './user.service';
import { Request, Response } from 'express';
import { CreateUserDTO } from './dto/create-user.dto';
@Controller('user')
export class UserController {
constructor(private userService: UserService) {}
//fetch an user
@Get('userfavs/:userID')
async getCustomer(@Res() res: Response, @Param('userID') userID: string) {
const user = await this.userService.getUser(userID);
if (!user) throw new NotFoundException('This user does not exist!');
return res.status(HttpStatus.OK).json({
username: user.username,
favs: user.favs,
});
}
@Put('addfav/:favID')
async updateUser(
@Req() req: Request,
@Res() res: Response,
@Param('favID') favID: string,
@Body() createUserDTO: CreateUserDTO,
) {
const user = await this.userService.updateUser(req.user._id, createUserDTO);
if (!user) throw new NotFoundException('This user does not exist!');
return res.status(HttpStatus.OK).json({
message: 'Fav added successfully!',
});
}
}
And here's the service code:
import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { User } from './interfaces/user.interface';
import { CreateUserDTO } from './dto/create-user.dto';
@Injectable()
export class UserService {
//creates Mongoose model for the User
constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
//fetch a specific user - useful for checking favorites
async getUser(userID: string): Promise<User> {
const user = await this.userModel
.findById(userID)
.populate('favs')
.exec();
return user;
}
//edit a specific user
async updateUser(
userID: string,
createUserDTO: CreateUserDTO,
): Promise<User> {
const updatedUser = await this.userModel.findByIdAndUpdate(
userID,
createUserDTO,
{ new: true },
);
return updatedUser;
}
}
In a Node.js environment, I would have approached this differently:
User.findByIdAndUpdate(req.user._id, {
$push: { favs: favId },
})
However, dealing with DTOs in Nest has been a bit confusing for me.