.populate() and find do not seem to work when looking for objects in an array

62 Views Asked by At

I have a service method that looks like this:

async getTeamsByNightId(id: string) {
    const night = await this.nightModel.findById({_id: id});
    console.log('night: ', night);
    //@TODO Why is populate not working?
    //const night = (await this.nightModel.findById({_id: id})).populate('teams');

    if (night) {
      const teamIds = night.teams.map((teamId) => teamId.toString());
      console.log('teamIds: ', teamIds);
      try {
        const teams = await this.teamModel.find({ _id: { $in: night.teams } }).exec();
        console.log('teams: ', teams);
      } catch (error) {
        console.log(error);
      }
      
    } else {
      throw new NotFoundException('No matching Night found');
    }
  }

And it is producing this output:

Mongoose: nights.findOne({ _id: ObjectId("6552ad936a93bab2b686496d") }, {})
night:  {
  _id: new ObjectId("6552ad936a93bab2b686496d"),
  name: 'a',
  askedQuestions: [],
  teams: [ new ObjectId("6552ada76a93bab2b6864972") ],
  password: '487254',
  __v: 1
}
teamIds:  [ '6552ada76a93bab2b6864972' ]
Mongoose: teams.find({ _id: { '$in': [ ObjectId("6552ada76a93bab2b6864972") ] } }, {})
teams:  []

As you can see it has an ObjectId in the teams array, but trying to look for this through all the teams yields no results.

There are the schemas:

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument, Types } from "mongoose";

export type NightDocument = HydratedDocument<Night>;

@Schema()
export class Night {
    @Prop()
    name: string;

    @Prop()
    password: string;

    @Prop([{ type: Types.ObjectId, ref: 'Question' }])
    askedQuestions: Types.ObjectId[];

    @Prop([{ type: Types.ObjectId, ref: 'Team' }])
    teams: Types.ObjectId[];;
}

export const NightSchema = SchemaFactory.createForClass(Night);

And Team

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';

export type TeamDocument = HydratedDocument<Team>;

@Schema()
export class Team {

  @Prop()
  username: string;

  @Prop()
  password: string;
}

export const TeamSchema = SchemaFactory.createForClass(Team);

And the way i add the objectIds from the Teams to the Night:

async addTeamToNight(teamId: string, addTeamToNightDTO: AddTeamToNightDTO) {
    const name = addTeamToNightDTO.name;
    const password = addTeamToNightDTO.password;
    const night = await this.nightModel.findOne({name, password}).exec();

    if (night) {
      night.teams.push(new Types.ObjectId(teamId));
      return await night.save();
    } else {
      throw new NotFoundException('Name or Password incorrect');
    }
  }

What am I doing wrong?

0

There are 0 best solutions below