डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

Full Stack Web Development with Laravel

Full Stack Web Development with Laravel

Affiliate Program

Affiliate Program

NEXT JS api with mongodb

import { ObjectId } from "mongodb";
import clientPromise from "../../lib/mongodb"

export default async  function handler(req, res) {    
    const client = await clientPromise;
    const db =  client.db("ctdb");   
    // console.log("at server");
    // console.log(req.body); 
    switch(req.method){
        case "GET":
            var users= await db.collection("users").find({}).toArray();  
            users = JSON.parse(JSON.stringify(users)); 
            res.status(200).json({ users:users });
            break;
        case "DELETE":                    
            var body=req.body;                
            var user=await db.collection("users").deleteOne({"_id":ObjectId(body.user_id)});
            res.status(200).json({ success:true });
            break;
        
        case "PUT":
            var body = req.body;
            var user = await db.collection("users").updateOne({"_id":ObjectId(body.user_id)},
                {$set: {name:body.name, email: body.email, password: body.password}});
            res.status(200).json({ success:true });
            break;
        case "POST": 
            var body=req.body;            
            console.log(body);
            var user=await db.collection("users").insertOne({
                name:body.name,
                email:body.email,
                password:body.password
            });
            res.status(200).json({ success:true, user: user });   
            break;
    }    
}
 
© 2016 - 2023, All Rights are Reserved.