使用typegoose将项目添加到Ref数组 [英] Add items to an Array of Ref with typegoose

查看:104
本文介绍了使用typegoose将项目添加到Ref数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个类扩展了Typegoose(ItemPlayer)

I got 2 classes extending Typegoose (Item and Player)

Player类中,我得到了Ref<Item>[]

    @arrayProp({itemsRef: Item})
    items?: Ref<Item>[];

在我的PlayersService中,我使用此方法来推送Item:

In my PlayersService, i use this method to push an Item:

    async pushItem( itemPlayerDto: {playerId: string, item: Item}) : Promise<Player> {
        let player = await this.findById(itemPlayerDto.playerId);
        player.items.push(itemPlayerDto.item);
        return await new this.playerModel(player).save();
}

但是当我检索到Players时,他们的items并没有被添加,只是一个Array of ObjectId.

But when i retrieve Players, their items are not pupolated, only an Array of ObjectId.

    async findAll(): Promise<Player[]> | null {
        return await this.playerModel.find().exec();
} 

PS:我正在将Typegoose与nestjs和netsjs-typegoose一起使用

PS: i'm using Typegoose with nestjs and netsjs-typegoose

推荐答案

好的,这就是从typegoose类填充Ref项目的方法(使用:populate方法):

Ok so this is how you can populate a Ref item from a typegoose class (use: populate method) :

async findByName(playerName: string): Promise<Player> | null {
    let player = await this.playerModel.findOne({'displayName': playerName}).exec();
    let playerWithItems = await player.populate({
        path: 'items',
        model: 'Item'
    }).execPopulate();
    return playerWithItems;
}

这篇关于使用typegoose将项目添加到Ref数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆