首页 > 解决方案 > 无法向 mongo db 文档添加新属性,我正在使用带有嵌套 js 的 typegoose

问题描述

这里我是如何注册 typegoose 的:

import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypegooseModule } from 'nestjs-typegoose';
import { getMongoConfig } from './configs/mongo.config';
import { ProcessModule } from './process/process.module';

@Module({
    imports: [
        ConfigModule.forRoot(),
        TypegooseModule.forRootAsync({
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory: getMongoConfig
        }),
        AuthModule,
        ProcessModule
    ]
})
export class AppModule {
}

这是我的服务文件,其中具有更新文档逻辑的功能。

import { InjectModel } from 'nestjs-typegoose';
import { MyModel } from './myModel.model';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { MyDto } from './dto/myDto.dto';


@Injectable()
export class MyService {
    constructor(@InjectModel(MyModel) private readonly myModel: ModelType<MyModel>) {
    }

    async functionToDo(dto: MyDto) {
        const addNewField = await this.myModel.findByIdAndUpdate(
            dto.id,
            {
                status: 1, // it was earlier in the db and I can update this field
                operator: 2 // this field is new and I want to add it, but it does not create
            },
            {
                new: true,
                useFindAndModify: false
            }
        ).exec();
    }
}

我已经使用了 mongoose 和 mongodriver 的各种更新功能,但它们都不起作用。$set 运算符也不起作用,它只是更新旧字段而不是创建新字段。

这是我要更新的文档的类型鹅模式。

import { prop } from '@typegoose/typegoose';
import { Base, TimeStamps } from '@typegoose/typegoose/lib/defaultClasses';
import { Types } from 'mongoose';

export interface MyModel extends Base {
}

export class MyModel extends TimeStamps {
    @prop({ type: () => Date, required: true })
    public created_at: Date;

    @prop({ type: () => Types.ObjectId })
    public user_id: Types.ObjectId;

    @prop({ type: () => String })
    public type: string;

    @prop({ type: () => String })
    public address: string;

    @prop({ type: () => Number })
    public status: number;

    @prop({type: () => Date, required: false})
    public updatedAt: Date;

    @prop({ type: () => Number })
    public operator: number; // this field did not exist before in the document.
}

即使我在指南针中手动添加此字段也不会更新,我尝试从 shell 添加新字段并且效果很好,所以 typegoose 的问题,请帮助我。

标签: mongodbmongoosenestjsmongoose-schematypegoose

解决方案


推荐阅读