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)
npm i @zaeny/mongodb
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}
}}
createDb,
connectDb,
getDb,
coll,
find,
query,
find,
transact
- Composable - Collection of functions to solve programming problem
- [1.0.0] add
query
andtransact