Home > OS >  NestJS mongoose return info from the database
NestJS mongoose return info from the database

Time:11-22

So, when i get the info from the MongoDB database in a NestJS service, i want to return it to the controller and send it to the client (Angular)

I tried returning it with a Promise but i cant get it working.

Heres my code with the thing a tried:

Service:

import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import mongoose, { Model } from "mongoose";
import {
  FriendRequest,
  FriendRequestDocument,
} from "../schema/friend-requests.schema";
import { Users, UsersDocument } from "../schema/user.schema";
import { FriendsDto } from "./dto/friends.dto";

@Injectable()
export class AddFriendService {
  constructor(
    @InjectModel(Users.name) private readonly usersModel: Model<UsersDocument>,
    @InjectModel("friendRequests")
    private readonly friendrequestModel: Model<FriendRequestDocument>
  ) {}

  async getRequests(userid: string) {
    
    
    let incomingrqs = new Promise((resolve, reject) => {
        let response = {
          incoming: [],
        };
        this.friendrequestModel
        .aggregate([
            {
              $lookup: {
                from: "users",
                localField: "author",
                foreignField: "_id",
                as: "userdata",
                // pipeline: [
                //   {
                //     $match: {
                //       friend_id: new mongoose.Types.ObjectId(userid)
                //     }
                //   }
                // ],
              },
            },
          ])
          .exec((err, data) => {
            if (err) {
              console.log(err);
            }
    
            if (!data) {
              console.log("No data returned");
            }
    
            data.forEach((rqsData) => {
              response.incoming.push({
                userid: rqsData.userdata[0]._id,
                username: rqsData.userdata[0].username,
                created_at: rqsData.userdata[0].created_at,
                pfp: "/assets/cdn/pfp/"   rqsData.userdata[0].pfp,
              });
            });
          });

          resolve(response);
      })

      incomingrqs.then(x => {
        return x;
      })
  }
}

Controller:

import { Get, Controller, Body, Post, Param } from "@nestjs/common";
import { AddFriendService } from "./friends.service";
import { FriendsDto } from "./dto/friends.dto";

@Controller("friends")
export class AddFriendController {
  constructor(private friendsService: AddFriendService) {}

  @Post("rqs")
  async getRqs(@Body() friendsDto: FriendsDto){

    let rqs = await this.friendsService.getRequests(friendsDto.userid);
    console.log(rqs)
    return rqs;
  }
}

FriendRequestDocument:

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import mongoose, { Document, ObjectId } from "mongoose";

export type FriendRequestDocument = FriendRequest & Document;

@Schema({collection: "friendRequests"})
export class FriendRequest {
  @Prop()
  author: mongoose.Types.ObjectId;

  @Prop()
  friend_id: mongoose.Types.ObjectId;

  @Prop()
  request_at: Date;
}

export const FriendRequestSchema = SchemaFactory.createForClass(FriendRequest);

Can you help me? Thanks!

CodePudding user response:

aggregate.exec can already return a promise if no callback is given, just FYI.

You need to return the incomingrqs to the controller. This is standard of how promises work.. Returning inside the then forwards the return on to the next promise, which is why the incomingrqs needs to be returned as well. Otherwise, the controller will never know what the service returns.

  • Related