【问题标题】:Unable to save nested data in MongoDB using NestJs and Mongoose无法使用 NestJs mongoose 在 mongodb 中保存嵌套数据
【发布时间】:2022-03-04 12:27:33
【问题描述】:

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

[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 发布时,可以在下面的屏幕截图中看到它已成功添加。那么为什么它不使用第一种方式添加

下面是我的代码:

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

有人让我知道我做错了什么。任何帮助将不胜感激。

【问题讨论】:

  • 打印console.log(userDto); 时是否可以查看日期
  • 是的,它在控制台中可见
  • 我已经在帖子中更新了user.service.ts 文件,看看我尝试使用原始 JSON 格式添加数据并添加了它,但为什么它不使用第一种方式添加。

标签: node.js mongodb mongoose nestjs mongoose-schema


【解决方案1】:

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

相反,您可以展开 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();
}
 

【讨论】:

  • 我正在尝试您的解决方案,但它抛出了同样的错误TypeError: Cannot set property 'city' of undefined
  • 如果我保存return await new this.userModel(userDto).save() 之类的数据并在原始 JSON 中发布正文,那么它会保存,但是当我使用您的解决方案并使用原始 JSON 发布时,它会显示相同的 TypeError
  • 我更新了答案以从控制器传递 data 对象而不是 DTO 现在检查。还在控制器调用服务中添加了等待
  • 还是一样的错误
  • 我认为您需要发送 JSON 原始格式,来自 POSTman 的嵌套表单数据很棘手,
【解决方案2】:

在邮递员中使用 Address.city,肯定会工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-26
    • 2021-02-17
    • 2014-11-09
    • 2018-12-23
    • 2015-07-18
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多