Search code examples
typescriptmongoosecrud

CRUD in Typescript with mongoose - query param checking


I want to add document to my DB collection only after checking all the req.query is like my IGroupDocument on the controller before inserting.

What is the best practice for 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) {
// req.query validation: if firstName, lastName and email exist and type string, and then make a document from req.query call newGroup.
    GroupModel.create(newGroup)
    res.send(`${req.query.name} created`)
}

Solution

  • You can read query parameters from request object like following:

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

    You can then pass these query parameters to your document create function like:

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

    The validation should take part in your mongoose schema. Since you did not include it, I just created a sample schema myself:

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

    Notes:

    • Passing values which are used for creating an object in query params is definitely a bad practice. You should pass them as the request body in a POST request.
    • You cannot call res.send('${req.query.name} created') directly after calling the create function. This returns a promise, which should be awaited. You can just use await GroupModel.create(...) and define the function as async.
    • You included req.query.name in your response, which is a query parameter that wasn't even used before. You should probably use a property from the awaited promise value.