Eyes, JAPAN Blog > How to install mongoDB on Arch Linux, using Prisma Schema Prototyping to sync mongoDB and auto generating graphQL Apollo Services

How to install mongoDB on Arch Linux, using Prisma Schema Prototyping to sync mongoDB and auto generating graphQL Apollo Services



This article will introduce How to install and use mongoDB on Arch Linux, using Prisma Schema Prototyping to sync mongoDB and auto generating graphQL Apollo Services.

① MongoDB Arch Linux (AUR)

MongoDB has been removed from the official repositories due to its re-licensing issues.

mongodb-bin – prebuilt MongoDB binary extracted from official MongoDB Ubuntu repository packages. Compilation options used are unknown.

② Install mongosh-bin (Dependency)

sudo mkdir Package
cd Package
sudo git clone https://aur.archlinux.org/mongosh-bin.git
sudo chmod -R 777 mongosh-bin
cd mongosh-bin

View the contents of PKGBUILD.


Make the package. After manually confirming the contents of the files, run makepkg as a normal user. Some helpful flags:

  • -i/--install installs the package if it is built successfully. This lets you skip the next step that is usually done manually.
makepkg -i

③ Install mongodb-bin

cd ..
sudo git clone https://aur.archlinux.org/mongodb-bin.git
sudo chmod -R 777 mongosh-bin
cd mongosh-bin
makepkg -i

④ Environment Configuration

Create a directory where the MongoDB instance stores its data.

sudo mkdir -p /var/lib/mongo

Create a directory where the MongoDB instance stores its log.

sudo mkdir -p /var/log/mongodb

The user that starts the MongoDB process must have read and write permission to these directories.

sudo chmod -R 777 /var/lib/mongo
sudo chown -R 777 /var/log/mongodb

⑤ Run MongoDB with a Replica Set deployed and create the User Administrator

To run MongoDB, run the mongod process at the system prompt.

mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork

Start a mongosh session on the same host machine as the mongod. You can run mongosh without any command-line options to connect to a mongod that is running on your localhost with default port 27017.

  • By default, MongoDB launches with bindIp set to, which binds to the localhost network interface. This means that the mongod can only accept connections from clients that are running on the same machine. Remote clients will not be able to connect to the mongod, and the mongod will not be able to initialize a replica set unless this value is set to a valid network interface.
    This value can be configured either:
    In the MongoDB configuration file with bindIp, or.
    Via the command-line argument --bind_ip.

  • Before binding to a non-localhost (e.g. publicly accessible) IP address, ensure you have secured your cluster from unauthorized access.


Convert a Standalone to a Replica Set.

  • Shut down the standalone mongod instance.
  • Restart the instance. Use the –replSet option to specify the name of the new replica set.
  • The rs.initiate() method provides a wrapper around the replSetInitiate command. Initiates a replica set.
mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork --replSet rs0

Use SCRAM to Authenticate Clients.

  • Start MongoDB without access control.
  • Connect to the instance.
  • Create the user administrator (root user).
  • Re-start the MongoDB instance.
show dbs
use admin
    user: "myUserAdmin",
    pwd: passwordPrompt(),
    roles: [
      { role: "userAdminAnyDatabase", db: "admin" },
      { role: "readWriteAnyDatabase", db: "admin" }
mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork --replSet rs0

⑥ Prisma Schema Prototyping

The MongoDB data source connector connects Prisma to a hosted MongoDB instance.

  • Create a project directory and navigate into it.
  • Create a tsconfig.json file and add configuration to it.
  • Invoke the Prisma CLI by prefixing it with npx.
  • Set up your Prisma project by creating your Prisma schema file.
    • prisma init Creates a new directory called prisma that contains a file called schema.prisma, which contains the Prisma schema with your database connection variable and schema models.
  • Install type-graphql package, as well as graphql and class-validator which are peer dependencies of TypeGraphQL.
  • The reflect-metadata shim is required to make the type reflection work.
    • We must ensure that it is imported at the top of our entry file (before we use/import type-graphql or our resolvers).
mkdir mongodb-graphql-nodejs
cd mongodb-graphql-nodejs
npm init -y
npm install -g typescript ts-node tslib
npm install prisma --save
npm install @types/node --save
npx prisma
npx prisma init
npm install typegraphql-prisma --save
npm install graphql class-validator type-graphql --save
npm install reflect-metadata --save
npm install @prisma/client apollo-server apollo-server-core --save

TypeScript configuration.

  • It’s important to set these options in the tsconfig.json file of our project.
    • TypeGraphQL is designed to work with Node.js LTS (10.3+, 12+) and the latest stable releases. It uses features from ES2018 so we should set our tsconfig.json file appropriately.
    • Due to using the graphql-subscription dependency that relies on an AsyncIterator, we may also have to provide the esnext.asynciterable to the lib option.
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "lib": ["esnext", "es2018", "esnext.asynciterable"],
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true

To connect to a MongoDB Server, configure the datasource block in your Prisma schema file.

use dataBase
show dbs

Prisma Integration.

  • TypeGraphQL provides an integration with Prisma by the typegraphql-prisma package.
    • It generates the type classes and CRUD resolvers based on the Prisma schema, so we can execute complex queries or mutations that corresponds to the Prisma actions, without having to write any code for that.
    • To make use of the prisma integration, first we need to add a new generator to the schema.prisma file.
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")

generator client {
  provider = "prisma-client-js"

generator typegraphql {
  provider = "typegraphql-prisma"

model User {
  id      String   @id @default(auto()) @map("_id") @db.ObjectId
  email   String   @unique
  name    String?
  role    Role     @default(USER)
  profile Profile?

model Profile {
  id     String @id @default(auto()) @map("_id") @db.ObjectId
  bio    String
  user   User   @relation(fields: [userId], references: [id])
  userId String @unique @db.ObjectId

enum Role {

model collection {
  id   String @id @default(auto()) @map("_id") @db.ObjectId
  item String
  qty  Int

The .env file in the root directory of the project, which is used for defining environment variables (such as your database connection).


Use db push to prototype a schema at the start of a project and initialize a migration history when you are happy with the first draft.

After running prisma generate we can import the generated resolvers classes and use them to build our graphQL schema.

prisma push --accept-data-loss

MongoDB CRUD Operations.

  • Use db.collection.remove() to remove the existing documents and reuse the collection. Use this approach to avoid flushing the cache.
show collections
db.collection.insertOne( { item: "card", qty: 15 } )

Bootstrapping graphQL Apollo Server.

  • After creating our resolvers, type classes, and other business-related code, we need to make our app run. First we have to build the schema, then we can expose it with an HTTP server, WebSockets or even MQTT.
    • Create Executable Schema.
      • To create an executable schema from type and resolver definitions, we need to use the buildSchema function. It takes a configuration object as a parameter and returns a promise of a GraphQLSchema object.
      • In the configuration object we must provide a resolvers property, which can be an array of resolver classes.
    • To make await work, we need to declare it as an async function. Example of main.ts file.
    • Create an HTTP GraphQL endpoint.
      • In most cases, the GraphQL app is served by an HTTP server. After building the schema we can create the GraphQL endpoint with a variety of tools such as graphql-yoga or apollo-server. Here is an example using apollo-server.
  • main.ts file as follows:
import "reflect-metadata";
import { resolvers } from "@generated/type-graphql";
import { PrismaClient } from "@prisma/client";
import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server";
import {
} from "apollo-server-core";
const prisma = new PrismaClient();
const PORT = process.env.PORT || 4000;
async function bootstrap() {
  const schema = await buildSchema({
    validate: false,
  const server = new ApolloServer({
    introspection: true,
    context: { prisma },
    plugins: [
      process.env.NODE_ENV === "production"
        ? ApolloServerPluginLandingPageDisabled()
        : ApolloServerPluginLandingPageGraphQLPlayground({
            settings: {
              "editor.theme": "dark" as const,
              "editor.reuseHeaders": true,
              "editor.fontSize": 16,
              "editor.fontFamily": `'Fira Code', 'Source Code Pro', 'Consolas'`,
  const { url } = await server.listen(PORT);
  console.log(`Server is running, GraphQL Playground available at ${url}`);

How to install mongoDB on Arch Linux, using Prisma Schema Prototyping to sync mongoDB and auto generating graphQL Apollo Services

⑦ References

[1]: https://wiki.archlinux.org/title/MongoDB
[2]: https://aur.archlinux.org/packages/mongosh-bin
[Arch User Repository]: https://wiki.archlinux.org/title/Arch_User_Repository
[3]: https://aur.archlinux.org/packages/mongodb-bin
[4]: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu-tarball/
[6]: https://www.prisma.io/docs/concepts/components/prisma-schema


Author: Yuzu
Link: https://kamisu66.com/2022/07/24/How-to-install-mongoDB-on-Arch-Linux-Manjaro/
Copyright Notice: This article is licensed under CC BY-NC-SA 4.0 unless stating additionally.

  • このエントリーをはてなブックマークに追加

Comments are closed.