Next.js Discord

Discord Forum

Is this a good way to make API requests in MONGO DB

Answered
Pigeon tremex posted this in #help-forum
Open in Discord
Pigeon tremexOP
import Model from "../../../../../API/Models/model";
import Connector from "../../../../../API/Connector/connector";
import { NextResponse } from "next/server";

interface ParamsType{
    id:string
}

export const PATCH=async (request:any, {params}:{params:ParamsType}):Promise<any>=>{
    await Connector();
    const {id}=params;
    const body=await request.json();
    const updatedData=await Model.findOneAndUpdate({_id:id},body,{new:true, runValidators:true});
    return NextResponse.json({message:"Data updated",updatedData},{status:200});
} 

export const GET=async (request:any,{params}:{params:ParamsType}):Promise<any>=>{
    await Connector();
    const {id}=params;
    const indvData=await Model.findOne({_id:id});
    return NextResponse.json({message:"Data fetching", indvData},{status:200});
}

export const DELETE=async (request:any, {params}:{params:ParamsType}):Promise<any>=>{
    await Connector();
    const {id}=params;
    const deletedData=await Model.findOneAndDelete({_id:id});
    return NextResponse.json({message:"Data deleted",deletedData},{status:200});
} 

Here while making every single request the connection to the database is done like first I want to make a GET request then firstly I go connect to the database and all. I used to work on Node and there only once the database connection happened. Is it not possible to make the database connection once like if the database connection does not happen the application won't load and then after that no connection required.
Also can I use that await Connector in the layout.tsx where there will be "use client" for the call of Connector function inside useEffect
Answered by B33fb0n3
I saw in prisma (that is more cloud) that connections are handled by the library. So if you can pass it away from your app you are good to go 👍
View full answer

13 Replies

@Pigeon tremex js import Model from "../../../../../API/Models/model"; import Connector from "../../../../../API/Connector/connector"; import { NextResponse } from "next/server"; interface ParamsType{ id:string } export const PATCH=async (request:any, {params}:{params:ParamsType}):Promise<any>=>{ await Connector(); const {id}=params; const body=await request.json(); const updatedData=await Model.findOneAndUpdate({_id:id},body,{new:true, runValidators:true}); return NextResponse.json({message:"Data updated",updatedData},{status:200}); } export const GET=async (request:any,{params}:{params:ParamsType}):Promise<any>=>{ await Connector(); const {id}=params; const indvData=await Model.findOne({_id:id}); return NextResponse.json({message:"Data fetching", indvData},{status:200}); } export const DELETE=async (request:any, {params}:{params:ParamsType}):Promise<any>=>{ await Connector(); const {id}=params; const deletedData=await Model.findOneAndDelete({_id:id}); return NextResponse.json({message:"Data deleted",deletedData},{status:200}); } Here while making every single request the connection to the database is done like first I want to make a GET request then firstly I go connect to the database and all. I used to work on Node and there only once the database connection happened. Is it not possible to make the database connection once like if the database connection does not happen the application won't load and then after that no connection required. Also can I use that await Connector in the layout.tsx where there will be "use client" for the call of Connector function inside useEffect
if you are self hosting, then the next server will be a node server.
if you deploy to vercel, netlify or other serverless platform, then it will create a new connection when a new function spin up
you cannot and should not doing database operation on client component
@Ray you cannot and should not doing database operation on client component
Pigeon tremexOP
ohh ohh oki. I am trying to make sure that my application is like rendered server side and all. So the correct method is to reconnect to the database every single time when every single route is called right? There is no such thing as first reconnect the database and connect it the entire time ?
Answer
By the way: I can recommend you graphql with aws amplify
@Pigeon tremex ohh ohh oki. I am trying to make sure that my application is like rendered server side and all. So the correct method is to reconnect to the database every single time when every single route is called right? There is no such thing as first reconnect the database and connect it the entire time ?
depend the driver you use, you can do something like this, i use mongodb as example
import { MongoClient } from "mongodb";

const mongoDbUrl = "mongodb://127.0.0.1:27017";
let mongodb;

function connect(callback) {
  mongoClient.connect(mongoDbUrl, (err, db) => {
    mongodb = db;
    callback();
  });
}
function get() {
  return mongodb;
}

function close() {
  mongodb.close();
}

export { connect, get, close };
@B33fb0n3 By the way: I can recommend you graphql with aws amplify
Pigeon tremexOP
ohh ok I will look into it thanks !!
@Ray depend the driver you use, you can do something like this, i use mongodb as example ts import { MongoClient } from "mongodb"; const mongoDbUrl = "mongodb://127.0.0.1:27017"; let mongodb; function connect(callback) { mongoClient.connect(mongoDbUrl, (err, db) => { mongodb = db; callback(); }); } function get() { return mongodb; } function close() { mongodb.close(); } export { connect, get, close };
Pigeon tremexOP
Yeah I have done something like this but using mongoose.
require("dotenv").config();

import mongoose from "mongoose";

const Connector=async () : Promise<void>=>{
    try{
        await mongoose.connect("<api string>");
    }
    catch(err){
        console.log("Error in connecting to the database ", err);
    }
}

export default Connector;


But my questions is when do we call the Connector function?
 Like connect the database at the very beginning and once it's connected then only load the application. This may need the use of useState and useEffect which will need use client and you recommended not to use in client side 


 Secondly can I put in every single request like suppose I want to get a list of request then

{
  await Connector();
  mongooseModel.find({})
}

like this for every single route present
also I am using app router so I cannot use getServerSideProps
Pigeon tremexOP
ohh wait I haven't got my answer yet lol !!
perfect, good job! 👍
lol