DEV Community

EmanSaeed331
EmanSaeed331

Posted on

1 1

How to make a CRUD operation By Nodejs and TypeScript .?

you can use a generic way to be applicable for any model you need, only you pass model and data type, and you can apply all crud operations on it.
source github

  • CREATE
   async function create<T>(data:T , model:any){
        const newObj = await new model(data);
        await newObj.save()
        return newObj;
Enter fullscreen mode Exit fullscreen mode
  • READ
    async function read(model:any){
        return await model.find({});
    }

Enter fullscreen mode Exit fullscreen mode
  • UPDATE

    async function update<T>(id:string, data:T , model:any){
        return  await model.findByIdAndUpdate(id,data); 
    }
Enter fullscreen mode Exit fullscreen mode
  • DELETE
   async function getById (id:string,model:any){
        const data = await model.findOne({id});
        if(!data) {
            return 'id is not valid';
        }
        return data ; 
    }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay