无法使用 NestJs mongoose 在 mongodb 中保存嵌套数据

Unable to save nested data in mongodb using NestJs mongoose

我正在创建应用程序,我在其中使用 NestJs 框架并使用 mongodb 数据库和 mongoose ORM 我有嵌套的数据结构,我试图将其保存在数据库中,但在保存时抛出错误。以下是我的错误:

[Nest] 11196  - 19/02/2022, 6:01:30 pm   ERROR [ExceptionsHandler] Cannot set property 'city' of undefined
TypeError: Cannot set property 'city' of undefined
at UserService.addUser (D:\nest\nested-schema-proj\src\user\user.service.ts:18:27)
at UserController.addUser (D:\nest\nested-schema-proj\src\user\user.controller.ts:11:33)

以下是邮递员要求:

当我将数据发布为原始数据时 JSON 可以在下面的屏幕截图中看到然后它被添加 successfully.Then 为什么它不使用第一种方式添加

下面是我的代码:

user.schema.ts

import mongoose from "mongoose";

const addressSchema = new mongoose.Schema({
  city:{type:String},
  state:{type:String}
});

export const UserSchema = new mongoose.Schema({

 name:{type:String},
 age:{type:Number},
 address:addressSchema

});


interface Address{
 city:string;
 state:string;
}

export interface AllUser{
 name:string;
 age:number;
 address:Address;
}

user.dto.ts

export class UserDto{
  name:string;
  age:number;
  address:Address
}

class Address{
  city:string;
  state:string;
}

user.controller.ts

import { Body, Controller, Post } from '@nestjs/common';
import { UserDto } from './dto/user.dto';
import { UserService } from './user.service';

@Controller()
export class UserController {
constructor(private userService:UserService){}

@Post('addUser')
addUser(@Body() userDto:UserDto){
    return this.userService.addUser(userDto);
  }
}

user.service.ts

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model} from 'mongoose';
import { UserDto } from './dto/user.dto';
import { AllUser } from './schema/user.schema';

@Injectable()
export class UserService {
constructor(@InjectModel('AllUser') private readonly userModel:Model<AllUser>){}

async addUser(userDto:UserDto): Promise<AllUser>{

    console.log(userDto);

     const data = new this.userModel();
     data.name = userDto.name;
     data.age = userDto.age;
     data.address.city = userDto.address.city; //Showing error in this line
     data.address.state = userDto.address.state;

     const result = await data.save();
     return result;

     //Posting data as a raw JSON as shown in 2nd screenshot
     // const data = new this.userModel(userDto);
     // const result = await data.save();
     // return result;  
   }
 }

有人让我知道我在做什么wrong.Any 帮助将不胜感激。

您无法保存,因为用户模型是在您的服务初始化时注入的接口对象。您也不能通过启动和访问其 属性.

来使用此模型

相反,您可以展开 DTO 并将其保存。如果你想从你的代码中,你也可以操纵你额外的字段。在下面的示例中,我添加了 date/time 的文档创建

 return await new this.userModel({
          ...userDto,
          created_at: moment.utc() //Manipulate your extra fields and set here
        }).save();

如果您需要再次在控制器级别处理数据并将该 DTO 直接传递给服务并保存它,您也可以设置自己的 DTO 对象

例如:

//In Controller
 const data = new UserDto();
 data.name = userDto.name;
 data.age = userDto.age;
 data.address.city = userDto.address.city; 
 data.address.state = userDto.address.state;
 data.created_at: new Date();
return await this.userService.addUser(data);

//Service:
async addUser(userDto:UserDto): Promise<AllUser>{

console.log(userDto);

 return await new this.userModel({
      ...userDto,
      created_at: moment.utc() //Manipulate your extra fields and set here
    }).save();
}
 

在 postman 中使用 Address.city,肯定有效