DEV Community

EmanSaeed331
EmanSaeed331

Posted on

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)