我有一个服务方法,看起来像这样:
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');
}
}
型
我做错了什么?
1条答案
按热度按时间pkmbmrz71#
要填充团队数组,您必须执行以下操作:
字符串
要将新的
teamId
添加到night
集合中,请执行以下操作:型
good luck ;)