# Redux Tutorial: Setup Database functions

Modify redux-todolist/data/database.js

Open redux-todolist/data/database.js in your favorite editor and add the following code:


import pmongo from 'promised-mongo';

const db = pmongo('reduxtest', ['todos']);

export function getTodo(_id) {
  return db.todos.findOne({ _id: pmongo.ObjectId(_id) });
}

export function getTodos() {
  return db.todos.find({});
}

export function createTodo(todo) {
  if (!todo) {
    return new Promise((resolve, reject) => {
      reject(`"todo" cannot be empty`);
    });
  }

  return db.todos.insert({ todo, completed: false });
}

export function removeTodo(_id) {
  return db.todos.remove({ _id: pmongo.ObjectId(_id) })
                 .then(() => {
                    return { _id: _id };
                 });
}

export function updateTodo(_id, todo, completed) {
  let todoItem = {
    todo, completed
  };

  if (!_id) return new Promise((resolve, reject) => {
    reject(`"_id" required to update Todo Item\n`);
  });

  if (!todo) delete todoItem.todo;
  if (typeof completed !== 'boolean') delete todoItem.completed;

  return db.todos.findAndModify({
            new: true, // return the newly modified document
            query: { _id: pmongo.ObjectId(_id) },
            update: { $set: todoItem } }).then(({ value }) => value);
}

We are using the promised-mongo library to connect to our backend MongoDB instance. We create a new pmongo connection to our reduxtest database and reference the todos collection.

We then define createTodo(todo), getTodo(id), getTodos(), updateTodo(id) and removeTodo(id) for CREATE, READ, UPDATE and DELETING our todo items. The code is pretty self-explanatory. The important point to note here is that we always return promises as it will make it easier to consume the result when we define our GraphQL schema. To know how to use these database functions to resolve requests to our GraphQL service, please navigate to the next section "Setup GraphQL Schema".