.populate() 和 find 似乎不起作用,我不知所措

问题描述 投票:0回答:1

我很茫然。我目前有一个如下所示的服务方法:

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

正如您所看到的,它在团队数组中有一个 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);
mongoose nestjs mongoose-populate objectid
1个回答
0
投票

如果

teams
ObjectId
的数组,那么您需要修改您的
teams
模式定义,如下所示:

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

根据您的设计,您可能还需要将

Team
模式导入到
Night
模式中。例如:

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument, Types } from "mongoose";
import { Team } from './path/to/team/schema';

export type NightDocument = HydratedDocument<Night>;

那么当您

populate
时,您可能需要通过
path

const night = await this.nightModel.findById({_id: id})).populate({path: 'teams'});
© www.soinside.com 2019 - 2024. All rights reserved.