无法使用NestJs和Mongoose在MongoDB中保存嵌套数据

icomxhvb  于 2022-12-13  发布在  Go
关注(0)|答案(2)|浏览(138)

I am creating application where I am using NestJs framework and using MongoDB database with Mongoose ORM. I have nested data structure that I am trying to save inside database, but it's throwing error when I am saving it.
Below is my error:

[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)

Below is my Postman request:

When I am posting data as raw JSON that can be seen in screenshot below then it is added successfully. Then why it not adding using first way?

Below is my code:

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;  
   }
 }

What am I doing wrong?

bpsygsoo

bpsygsoo1#

您无法保存,因为用户模型是在初始化服务时注入的接口对象。此外,您也无法通过初始化和访问其属性来保存此模型。
相反,你可以展开DTO并保存它。如果你想从你的代码中操作额外的字段,你也可以。在下面的例子中,我添加了文档创建的日期/时间

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();
}
ktca8awb

ktca8awb2#

在Address.city Postman 中使用www.example.com,肯定会起作用

相关问题