Creating Node project with Express, MongoDB, Typescript & GraphQL involves several steps. Lets discuss them in detail as follows:
Prerequisites:
Before getting into the steps to create a node project, let’s make sure the system is installed with node , VS Code, and Mongo DB softwares.

Step 1 : Create the server folder and navigate into it.
mkdir server
cd server

Step 2: Initialize the project
yarn init -y

Step-3 : Install all packages with typescript dependencies
yarn add express graphql express-graphql mongoose dotenv mongodb cors

yarn add typescript ts-node @types/node @types/express @types/graphql @types/mongoose @types/dotenv  @types/mongodb -D

Step 4: Setup config.ts file in the project root folder:
{

  “compilerOptions”: {

    “target”: “ES6”,

    “module”: “commonjs”,

    “strict”: true,

    “esModuleInterop”: true,

    “skipLibCheck”: true,

    “forceConsistentCasingInFileNames”: true,

    “outDir”: “./dist”,

    “rootDir”: “./src”

  },

  “include”: [“src”],

  “exclude”: [“node_modules”]

}


Step 5: Setup .env file in the project root folder
MONGO_URI=mongodb://localhost:27017/mydatabase

PORT=4000

Step 6: Create folders & files under the project root
mkdir src

touch src/index.ts src/database.ts src/schema.ts src/models/User.ts

Step 7: create database.ts file for DB connection

import express from 'express';
import dotenv from 'dotenv';
import connectDB from './database';
dotenv.config();
const app = express();
const port = process.env.PORT || 4000;
connectDB();
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}/graphql`);
});

Step 8: Update package.json

  "scripts": {

    “start”: “nodemon –exec ts-node src/index.ts”,

    “build”: “tsc”,

    “test”: “jest”

  },
Step 9: Create models, schemas, resolvers and update them in index.ts file:
import express from “express”;

import dotenv from “dotenv”;

import connectDB from “./databse”;

import { ApolloServer } from “apollo-server-express”;

import usertypeDefs from “./schema/userschema”;

import userresolvers from “./resolvers/userResolvers”;

import UserModel from “./models/usermodel”;

dotenv.config();

connectDB();

const startServer = async () => {

  const app = express();

  const server = new ApolloServer({

    typeDefs: [usertypeDefs],

    resolvers: [userresolvers],

    context: {

      UserModel,

    },

  });

  await server.start();

  server.applyMiddleware({ app });

  var PORT = process.env.PORT;

  app.listen(PORT, () => {

    console.log(`Server running at http://localhost:${PORT}`);

  });

};

startServer();

Step 10: Run the project
yarn start

Hence, the project gets started and we could see the mongodb connection and server running on port in the console message.

Leave a Reply