An error occurred in the ExceptionsHandler while trying to validate the city: weather field. The casting to string operation

My goal is to develop a city and then use the OpenWeatherMap API to fetch the weather information for that city, which will be stored in a MongoDB Atlas database.
However, I am facing an issue with defining the correct schema type for the weather field. Although I attempted to use 'Mixed', it seems to be unrecognized.

Project Structure

|- cities
|- |  city.model.ts
|- |  cities.controller.ts
|- |  cities.service.ts

city.model.ts

import * as mongoose from 'mongoose';

export const CitySchema = new mongoose.Schema({
  name: String,
  weather: String,
});

export interface City {
  id: number;
  name: string;
  weather: mongoose.Mixed;
}

cities.controller.ts

@Controller('cities')
export class CitiesController {
  constructor(private readonly citiesService: CitiesService) {}

  @Post()
  createCity(@Body() createCityDto: CreateCityDto) {
    return this.citiesService.createCity(createCityDto);
  }
}

cities.service.ts

@Injectable()
export class CitiesService {
  constructor(
    @InjectModel('City') private readonly cityModel: Model<City>,
    private readonly httpService: HttpService
    ) {}

  async createCity(createCityDto: CreateCityDto) {
    const { name } = createCityDto;

    // Fetching city weather data from OpenWeatherMap
    const weather = this.httpService
      .get(
        `api.openweathermap.org/data/2.5/weather?q=${name}&appid=${process.env.OPEN_WEATHER_API_KEY}`,
      )
      .pipe(map((response) => response.data));

    const city = new this.cityModel({
      name,
      weather,
    });

    await city.save();

    return city;
  }
}

cities.module.ts

...

@Module({
  imports: [
    HttpModule,
    MongooseModule.forFeature([{ name: 'City', schema: CitySchema }]),
  ],
  controllers: [CitiesController],
  providers: [CitiesService],
})
export class CitiesModule {}

Error Log

[Nest] 12852  - 22/12/2021, 10:35:21     LOG [NestApplication] Nest application successfully started +7ms
[Nest] 12852  - 22/12/2021, 10:35:27   ERROR [ExceptionsHandler] City validation failed: weather: Cast to string failed for value "Observable {
  source: Observable { _subscribe: [Function (anonymous)] },
  operator: [Function (anonymous)]
}" (type Observable) at path "weather"
ValidationError: City validation failed: weather: Cast to string failed for value "Observable {
  source: Observable { _subscribe: [Function (anonymous)] },
  operator: [Function (anonymous)]
}" (type Observable) at path "weather"
    at model.Document.invalidate (C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\mongoose\lib\document.js:2921:32)
    at model.$set (C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\mongoose\lib\document.js:1458:12)
    at model.$set (C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\mongoose\lib\document.js:1153:16)
    at model.Document (C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\mongoose\lib\document.js:158:12)
    at model.Model (C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\mongoose\lib\model.js:107:12)
    at new model (C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\mongoose\lib\model.js:4777:15)
    at CitiesService.createCity (C:\Users\ouss\Desktop\coffeeit-assessment\src\cities\cities.service.ts:29:18)
    at CitiesController.createCity (C:\Users\ouss\Desktop\coffeeit-assessment\src\cities\cities.controller.ts:11:31)
    at C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\@nestjs\core\router\router-execution-context.js:38:29
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

Answer №1

After implementing the following code snippet, it appears to be functioning correctly

import * as mongoose from 'mongoose';

export const CitySchema = new mongoose.Schema({
  name: String,
  weather: mongoose.SchemaTypes.Mixed,
});

export interface City {
  id: number;
  name: string;
  weather: mongoose.Mixed;
}

I welcome any feedback or suggestions for improvement on this code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on bundling a TypeScript Language Server Extensions LSP using WebPack

Currently, I am working on a language server extension for vs-code that is based on the lsp-sample code. You can find the code here: https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample My challenge lies in WebPacking the extension ...

Encountered an issue with Vue 3 defineProps(): [plugin:vite:vue] Transformation unsuccessful

Currently, I am utilizing Vue version 3.2 along with TypeScript. Whenever I try to declare my props in the following manner: <!-- AppButton.vue --> <script lang="ts"> interface Iprops { buttonType?: string; size?: strin ...

Exclude the document from the output if it belongs to a different collection

Within my application, I have three main collections: assign, checkin, and asset. When navigating to the /assign page, I execute a query as follows: Asset.find({"author.id":req.user.id}, function(err, allAsset) { if(err){ console.log(err ...

Angular 5 combined with the dynamic capabilities of Popper.JS

Launching a training project that requires Popper.Js in its features has been quite challenging. Despite following Bootstrap's documentation on how to implement Popper.Js, I have encountered difficulties. As per Bootstrap's docs, I tried initiat ...

Storing EAV data: Examining the Pros and Cons of XML versus NoSQL / MongoDB

For my web app, I am utilizing the EAV pattern to store data in a MySQL database. This method involves storing each attribute of an object as its own row in a table. Here is a simplified example of what I am working with... OBJECTS ATTRIBUTES ...

searching for a specific document within a sub array of a document in MongoDB using Java and MongoDB

Trying to figure out the best way to retrieve nodes.index where radio.mac_address="00:06:5A:03:2E:5B" in MongoDB using Java. Here is my MongoDB setup. I've attempted several queries, one of which is: BasicDBObject query = new BasicDBObject("nodes.ra ...

Generate a React App with TypeScript: Only transpile, skip type checking and linting

Need help optimizing the deployment of my small React project on a Google Compute Engine instance with limited RAM of under 1.5 GB. During the production build, the typescript linter and compiler consistently consume around 2 GB of RAM, which causes the C ...

Error: Module 'redux/todo/actions' could not be located. Please check the file path

Despite reading numerous posts and articles on getting absolute imports to work in a TypeScript project, I have not encountered any issues with this. My project is functioning properly with absolute imports. However, within VS Code, all absolute imports a ...

Interacting between Angular Child and Parent components

I am facing an issue where I am trying to emit an event from a child component and display it in the parent HTML, but it doesn't seem to be working. Below is my code: ParentComponent.ts @Component({ selector: 'app-parent', templateUrl: ...

Retrieving and setting data in ReactJS

Currently utilizing Reactjs in tandem with MongoDB. Once a user makes a selection in Reactjs, that value is then sent over to MongoDB. addTodo(event) { event.preventDefault(); var roomID = this.state.selectedRoomID; console.log(Ro ...

Attempting to build a table within a table structure

My goal is to create a nested table structure similar to this image: https://i.sstatic.net/v6lZo.png The number of months, topics, and arguments for each topic can vary as they are retrieved from a database. I have attempted to implement this functionali ...

What is the best way to arrange this script?

I am currently working on a Javascript script that automatically scrolls down and loads a new URL when it reaches the bottom of the page. However, I would like to add a delay of 30 seconds before the new URL is loaded. Although I am relatively new to Java ...

What is the best way to convert an Express route to Typescript?

I'm trying to create a wrapper called loginRequired for my Express route, but I'm struggling to define the right types. This is what my loginRequired wrapper looks like: export const loginRequired = (fn) => (req, res, next) => { // Ch ...

Using the Go programming language to replay the oplog on a separate MongoDB instance from an active primary instance in a cluster

I am currently managing oplogs in json format from the primary mongodb instance running on my system. [{"Timestamp":6477723955623886852,"HistoryID":166676398345289971,"MongoVersion":2,"Operation":"i","NameSpace":"test.tests","Object":{"__v":0,"_id":"59e57 ...

Errors in type checking observed in app.reducer.ts file for Angular NgRx

I encountered an issue with my login/logout state management setup. The error message I received is as follows: When trying to assign '(state: State | undefined, action: authActions) => State' to type 'ActionReducer<State, Action>& ...

Is there a way to retrieve student data by searching for a specific field?

I have a search button on the front end that allows users to input a student number and retrieve the corresponding information from my schema... Currently, I am mapping the data for all products However, when attempting to log the data, I am getting a nu ...

Exploring MongoDB with C# for Asynchronous Cursor Explanation

I currently have a text index in my data and am using regex search to make sure the correct index is utilized. While I have been able to use explain in the mongo shell, I am unsure how to do the same in the C# driver. Below is the code snippet illustratin ...

Angular application code modifications do not reflect in the browser

After making changes to the HTML file of an Angular component, the browser does not reflect those changes when connected to localhost. Even though the old string is no longer present in the project, the browser continues to display it. Interestingly, openi ...

Incorporate JavaScript features into a Node.js Express application to create an interactive slideshow

I recently started working with NodeJS on a significant project. My tech stack includes NodeJS, Express, and MongoDB. I had been using vanilla JS code to fetch dummy data and manipulate HTML via the DOM. However, I now realize that I cannot use the DOM in ...

Issue with Ionic 3 types while using the copyTo function on fileEntry

While working on my Ionic 3 app, I encountered an issue when trying to copy a file to a new directory using the Cordova plugin file. The error message states: Argument of type 'Entry' is not assignable to parameter of type 'DirectoryEntry&a ...