populate似乎在nestjs mongoose中不起作用

piwo6bdm  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(140)

我有一个服务方法,看起来像这样:

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');
    }
  }

字符串
它正在产生这样的输出:

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:  []


正如您所看到的,它在teams数组中有一个ObjectId,但是尝试在所有团队中查找它不会产生任何结果。
有以下模式:

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);


和团队

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);


我将团队中的objectId添加到夜晚的方式是:

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');
    }
  }


我做错了什么?

pkmbmrz7

pkmbmrz71#

要填充团队数组,您必须执行以下操作:

const teams = await this.nightModel.find({ _id: nightId })
.populate({ path: "teams", model: Team.name })

字符串
要将新的teamId添加到night集合中,请执行以下操作:

const night = await this.nightModel.findOneAndUpdate({ _id: nightId },{$push:{teams: new Types.ObjectId(teamId) }})


good luck ;)

相关问题