Skip to main content

Integrate with MongoDB

MongoDB is a flexible document database system that stores data in JSON-like documents.

Official Website: https://www.mongodb.com

Documentation: http://mongodb.github.io/node-mongodb-native/
NPM: https://www.npmjs.com/package/mongodb
Source Code: https://github.com/mongodb/node-mongodb-native

Getting started

  1. Create a MongoDB client in /less/shared/mongodb_client/index.js.

    /less/shared/mongodb_client/index.js
    const { MongoClient } = require('mongodb');

    const MONGODB = {
    URI: 'mongodb+srv://YOUR_MONGODB_URI',
    DATABASE_NAME: 'YOUR_DATABASE_NAME',
    COLLECTION_NAME: 'YOUR_DATABASE_COLLECTION'
    };

    let client;
    const connect = async () => {
    if (!client) {
    client = new MongoClient(MONGODB.URI);
    await client.connect();
    }
    };

    const insert_item = async (item) => {
    await connect();
    const db = client.db(MONGODB.DATABASE_NAME);
    const collection = db.collection(MONGODB.COLLECTION_NAME);
    return await collection.insertOne(item);
    };

    const list_items = async () => {
    await connect();
    const db = client.db(MONGODB.DATABASE_NAME);
    const collection = db.collection(MONGODB.COLLECTION_NAME);
    return await collection.find().toArray();
    }

    module.exports = {
    insert_item,
    list_items
    };
  2. Create a POST /items route in /less/apis/demo/items/post.js.

    /less/apis/demo/items/post.js
    const { insert_item } = require('mongodb_client');

    exports.process = async (request, response) => {
    const payload = JSON.parse(request.body);
    await insert_item(payload);
    response.body = JSON.stringify(payload);
    response.statusCode = 201;
    return response;
    };
  3. Create a GET /items route in /less/apis/demo/items/get.js.

    /less/apis/demo/items/get.js
    const { list_items } = require('mongodb_client');

    exports.process = async (request, response) => {
    const result = await list_items();
    response.body = JSON.stringify(result);
    response.statusCode = 200;
    return response;
    };
  4. Deploy!

    less-cli deploy YOUR_PROJECT_NAME