GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Nullstack
  • What is Nullstack?
  • Documentation
  • Examples
  • Contributors
  • F.A.Q
  • Waifu
  • Português
  • Star
  • Leave a star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing nullstack.app — How to use MongoDB - Nullstack

How to use MongoDB

According to mongodb.com:

"MongoDB is a general purpose, document-based, distributed database built for modern application developers and for the cloud era."

You can use any database with Nullstack, but the JavaScript integration and flexibility of MongoDB looks especially good with Nullstack applications.

Install the MongoDB driver from npm:

npm install mongodb

Configure the database credentials using secrets in your .env file.

NULLSTACK_SECRETS_MONGODB_URI="mongodb://localhost:27017/dbname"
NULLSTACK_SECRETS_DATABASE_NAME="dbname"

The last step is to simply assign the database connection to the server context.

// server.js
import Nullstack from 'nullstack';
import Application from './src/Application';
import { MongoClient } from 'mongodb';

const context = Nullstack.start(Application);

context.start = async function() {
  const { secrets } = context;
  const databaseClient = new MongoClient(secrets.mongodbUri);
  await databaseClient.connect();
  context.database = await databaseClient.db(secrets.databaseName);
}

export default context;

The example above will make the database key available to all your server functions.

import Nullstack from 'nullstack';

class BooksList extends Nullstack {

  books = [];

  static async getBooks({database}) {
    return await database.collection('books').find().toArray();
  }

  async initiate() {
    this.books = await this.getBooks();
  }

  // ...

}

export default BooksList;
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.