我有一个如下所示的服务方法:
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);
我做错了什么?
如果
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'});