我可以使用来自 Nest.js 中另一个模块中的控制器内的外部模块的服务创建注册表吗?

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

我有一个名为

MainController
的主控制器,当我调用“Put”并更新记录时,根据此函数中的某些情况,我需要调用一个函数来创建另一个模块中的服务的新记录:'其次.service.ts',这里是否可以创建一个对象并将其发送到该函数以创建另一个服务的新记录?

尝试一下,在更新主记录时,如果一切正常,我想从其他外部服务创建一条记录,尝试使用我需要发送到该服务的创建函数的数据创建一个对象,但它给出了我的错误:

Cannot set property 'name' of undefined

@Put(':id')
async update(@Param('id') id: number, @Body() data: UserDocument ) {
    let response = await this.userService.update(id, data);
    if (response.ok == 1) {
        // Find user register
        let user = await this.userService.findOne(+id);

        // Create object StoreMainDocument
        let storeMain: storeMainDocument
        storeMain.name = user.name;
        storeMain.url = user.path;
        storeMain.type = "Type";
        storeMain.user_id = user._id;

        console.log("storeMain", storeMain)

        // Send object and create register
        await this.storeMainService.create(storeMain);
    }
    return response;
}

这是线上获得的错误:

storeMain.name = user.name;

Error

我不确定这是否是正确的方法,或者创建“StoreMainDocument”类型的对象(它接收外部服务“this.storeMainService.create(storeMain)”的功能)必须以另一种方式完成。

这是我尝试从其他控制器使用的外部服务的“创建”功能:

public async create(storeMainDoc: StoreMain): Promise<StoreMain> {
    let nextCodeFromDb = await this.storeMainModel.findOne().sort({ code: -1 }).lean();
    if (!nextCodeFromDb) nextCodeFromDb = new StoreMain({code:0});
    storeMainDoc.code = nextCodeFromDb.code + 1;

    const createModel = await new this.storeMainModel(storeMainDoc);
    return await createModel.save();
}

我不确定这是否是正确的方法。我该如何解决它?

javascript typescript mongoose nestjs
1个回答
0
投票

您没有初始化 storeMain 变量:

let storeMain: storeMainDocument

初始化看起来像这样:

let storeMain: storeMainDocument = {
  name: user.name,
  url: user.path,
  ...and so on
}

另外,我不确定

storeMainDocument
是否是正确的类型,通常类型以大写字母开头,但这取决于你。

© www.soinside.com 2019 - 2024. All rights reserved.