@zaeny/mongodb

1.0.0 • Public • Published

@zaeny/mongodb

npm version

Mongodb utility pure functions

Wrap mongodb node.js driver so it expose only two main function query and transact, so you can seperate pure function in domain business and side-effect (avoiding not dot notation call)

Getting started

npm i @zaeny/mongodb

Usage

process.env.MONGODB_URI="mongodb://mongouser:mongopass@localhost:27017/test?authSource=admin&tls=false";

var {createDb, connectDb, query, transact} = require('@zaeny/mongodb');

var clientDb = createDb(process.env.MONGODB_URI);

connectDb(clientDb)
  .then(()=> console.log('mongodb connected');

var db => clientDb;

find({
  $db: "test",
  $coll: "tutorial",
  $where: {_id: 1}
}, db).then(console.log);

query([
  {$db: "test", $coll: "tutorial"},
  {$match: {}},
  {$project: {_id: 0, title: 1}},
  {$limit: 10}
], db).then(console.log);

query([
  {$db: "test", $coll: "tutorial"},
  {$group:{_id: null, total: {$sum: 1}}}
], db).then(console.log);

transact([
  {$db: "test", $coll: "tutorial"},
  {$create: {title: "why this is happen", description: "Just tutorial", published: false}}  
], db).then(console.log);

in the query the first query is always select database and collection by defining $db and $coll

{$db: "test", $coll: "tutorial"},

the rest of it is aggregate function to getting the data

...,
{$match: {_id: 1}},
{$sample:{size: 10}},
...

then we can implement onion architecture to seperate side-effect and the main core business

// core pure
var findUserByUsername = (username) => [
  {$db: 'my_db', $coll: 'story'},
  {$match:{ username }},
  {$limit: 1}
];

// controller api
await query(findUserByUsername(req.query.username));

inserting bulk, updating and deleting data with this api $create, $update, $updateMany, $delete, $deleteMany

example of usage transacting

...,
{$create: {title: "why this is happen", description: "Just tutorial", published: false}}
{$update: {
  $match: {title:/why/},
  $set: { updated_at: Date.now() }
}},
{$delete: {
  $match: {_id: 1}
}}

API

 createDb,
 connectDb,
 getDb,
 coll,
 find,
 query,
 find,
 transact

Related work

  • Composable - Collection of functions to solve programming problem

Changes

  • [1.0.0] add query and transact

Package Sidebar

Install

npm i @zaeny/mongodb

Weekly Downloads

3

Version

1.0.0

License

ISC

Unpacked Size

5.13 kB

Total Files

3

Last publish

Collaborators

  • azizzaeny