Performing CRUD operations in Typescript using mongoose with query parameter validation

Before inserting a document into my DB collection, I need to ensure that all the data in req.query matches the structure of my IGroupDocument in the controller.

What is the recommended approach for achieving this?

IGroupDocument:

import { Document, Model } from "mongoose";

export interface IGroup {

    firstName: string;
    lastName: string;
    age?: number;
    email: string,
    dateOfEntry?: Date;
}

export interface IGroupDocument extends IGroup, Document {}

Controller:

function create(req: Request, res: Response) {
// Validate req.query: check for existence of firstName, lastName, and email as strings, then create a new document using req.query and call it newGroup.
    GroupModel.create(newGroup)
    res.send(`${req.query.name} created`)
}

Answer №1

Extracting query parameters from a request object can be achieved like this:

const { firstName, lastName, email } = req.query;

You can then utilize these query parameters in your document creation function as follows:

GroupModel.create({firstName, lastName, email});

It is essential to handle validation within your mongoose schema. In case it was not included, you can create a basic schema example like this:

  const groupSchema = new Schema({
    firstName: { type: String, required: true },
    lastName: { type: String, required: true},
    email: { type: String, required: true }
  })

Important Notes:

  • Avoid passing critical values for creating an object through query parameters; instead, use the request body in a POST request.
  • Remember that calling
    res.send('${req.query.name} created')
    directly after the create function may cause issues. The function returns a promise that should be awaited. Consider using await GroupModel.create(...) and specify the function as async.
  • In your response, you referenced req.query.name, which wasn't utilized previously. Make sure to use properties from the resolved promise value instead.

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

Webpack compatibility issue hindering big.js node module functionality

I'm currently working on compiling (typescript files) and bundling my source code using webpack. Below is the content of my webpack.config.js file: const path = require('path') module.exports = { devtool: 'eval-source-map', en ...

Protector of the young travelers' paths

I have encountered a recurring issue with implementing Guards on my pages. Despite referencing multiple solutions from StackOverflow, none of them seem to work for me. Take this example for instance. This is my first attempt at restricting access to cert ...

What is a way to construct an object without resorting to casts or manually declaring variables for each field?

Click here for a hands-on example. Take a look at the code snippet below: export type BigType = { foo: number; bar?: number; baz: number; qux?: string[]; }; function BuildBigType(params: string[]) { // Here's what I'd like to do: ...

Angular: Exploring the most effective strategies for optimizing code within the ".subscribe()" method

Imagine having a component structured like this The Initial Code: import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<pre>{{ ...

Creating a date format for a REST API using Typegoose and Mongoose

Currently, I am utilizing TypeScript for a server that is connected to a MongoDB database. To ensure consistency, I am defining the outputs using an OpenAPI file. When working with Mongoose, I have experience in defining dates like this: birthday: Dat ...

"An error in the signature index results in the failure of the

I'm encountering a coding issue that's puzzling me. The TypeScript index signature I included in my code is as follows: const ships: { [index: string]: Ship } = {}; This snippet of code contains the problematic line: recieveAttack(e: any) { ...

Perfecting compound types

Having trouble with this code snippet: type FormatTypes = { text: string, binary: Array<number> }; type Format = keyof FormatTypes; type FormatType<F extends Format> = FormatTypes[F]; type Formatter = { format<F extends Format& ...

Develop a React Context that provides access to 2 additional functions via the Context Provider

I'm fairly new to ReactJS and TypeScript and seeking assistance in developing a react component that allows me to invoke methods. I am aware that there may be errors in my code. Below is the snippet. import { SomeExternalPackage } from "@external ...

Adjusting the appearance of a heading through CSS upon being clicked

My goal is to create a feature that highlights the border of a selected box in a different color. I attempted to achieve this by using classes in the TypeScript file and utilizing document.getElementById within the selectFlight method, which is called in t ...

Why does the alert modal I created in ShadCn automatically close as soon as I click on it?

There is an action that I created which displays a menu, and I implemented a function where if the user selects delete, a warning alert is shown before proceeding. However, the issue I am facing now is that when I click on the menu, the modal opens but imm ...

The visibility of the button is dependent on refreshing the page with the F5

I'm currently experiencing an issue with my code. The backoffice button is not showing up when I log in as an admin, unless I refresh the page by pressing F5. useEffect(() => { // Ensure window.FB and window.FB.XFBML are defined before calling ...

The limitations of Typescript when using redux connect

Recently, I utilized TypeScript for React to declare a class with constraints and now I'm looking to implement the connect method. Here is the code snippet: import * as React from 'react'; import { connect } from 'react-redux'; im ...

Is it advisable to generate a distinct model (collection) for this specific case?

Currently in the process of developing a small web application using MERN stack. The database collection I have set up includes fields for "name, email, password, avatar URL, and date". I am considering adding additional information for users such as a "bi ...

In order to work with Mongoose and Typescript, it is necessary for me to

I am currently following the guidelines outlined in the Mongoose documentation to incorporate TypeScript support into my project: https://mongoosejs.com/docs/typescript.html. Within the documentation, there is an example provided as follows: import { Sche ...

Looking to discover the hidden treasures nestled within the array fields?

{ "_id" : 1, "password" : "$2a$10$09XFcS7kSOpZBepd/uS8sO/5a7WU2B68L18TrC/EJ2Jjf3zX3mc8C", "username" : "neetu", "name" : "neetu12", "__v" : 3, "Address" : "America", "DOB" : ISODate("2000-03-05T00:00:00.000Z"), "Email" : "<a href="/cdn-cgi/l/email-prote ...

Sorting by Date in JavaScript

My goal is to filter out the elements in an array that have a date (converted from string) greater than a specific date. _this.downloadData.forEach(_d => _d.LogTime = _d.LogTime.toString()); console.log(_this.downloadData.filter(x=>new Date(x.LogTi ...

Exploring ways to fetch documents from a Mongoose database

I have a collection with multiple documents, each containing a long string. I need to retrieve one document at a time, as the documents only contain a long string. How can I achieve this? I used the insertMany() function to insert all documents into the c ...

What is the reason that the values in the select option only appear once it has been clicked on?

After loading or reloading the page, I am experiencing an issue where the select options do not appear on the first click and the values are not displayed until the second click. Any assistance would be greatly appreciated! I am still new to coding, so ple ...

Troubleshooting: Issues with importing Less files in TypeScript using Webpack and css-loader

I am currently working on a test project using TypeScript and Webpack. I have an index.ts file and a base.less (or base.css) file imported in the index.ts, but I am experiencing errors with the css-loader. Interestingly, everything works fine when the LESS ...

Exporting a class from an index.ts file may result in a problem where the injected constructor is

Utilizing an index.ts file to manage exports, following the guidelines outlined in the Angular 2 style guide (https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure), has been successful throughout my application deve ...