{"id":26095257,"url":"https://github.com/thenativeweb/node-viewmodel","last_synced_at":"2025-10-11T09:09:27.767Z","repository":{"id":3088037,"uuid":"4112387","full_name":"thenativeweb/node-viewmodel","owner":"thenativeweb","description":"Node-viewmodel is a node.js module for multiple databases. It can be very useful if you work with (d)ddd, cqrs, eventdenormalizer, host, etc.","archived":false,"fork":false,"pushed_at":"2020-09-04T03:26:05.000Z","size":453,"stargazers_count":27,"open_issues_count":6,"forks_count":20,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-12T10:06:54.056Z","etag":null,"topics":["cqrs","javascript","multiple-databases","read-model","viewmodel"],"latest_commit_sha":null,"homepage":"http://cqrs.js.org/pages/viewmodel.html","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thenativeweb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-04-23T11:33:29.000Z","updated_at":"2023-12-13T09:51:07.000Z","dependencies_parsed_at":"2022-09-19T20:16:18.724Z","dependency_job_id":null,"html_url":"https://github.com/thenativeweb/node-viewmodel","commit_stats":null,"previous_names":["adrai/node-viewmodel"],"tags_count":85,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thenativeweb%2Fnode-viewmodel","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thenativeweb%2Fnode-viewmodel/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thenativeweb%2Fnode-viewmodel/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thenativeweb%2Fnode-viewmodel/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thenativeweb","download_url":"https://codeload.github.com/thenativeweb/node-viewmodel/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248550635,"owners_count":21122933,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cqrs","javascript","multiple-databases","read-model","viewmodel"],"created_at":"2025-03-09T13:15:19.695Z","updated_at":"2025-10-11T09:09:22.703Z","avatar_url":"https://github.com/thenativeweb.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ⚠️ IMPORTANT NEWS! 📰\n\nI’ve been dealing with CQRS, event-sourcing and DDD long enough now that I don’t need working with it anymore unfortunately, so at least for now this my formal farewell!\n\nI want to thank everyone who has contributed in one way or another.\nEspecially...\n\n- [Jan](https://github.com/jamuhl), who introduced me to this topic.\n- [Dimitar](https://github.com/nanov), one of the last bigger contributors and maintainer.\n- My last employer, who gave me the possibility to use all these CQRS modules in a big Cloud-System.\n- My family and friends, who very often came up short.\n\nFinally, I would like to thank [Golo Roden](https://github.com/goloroden), who was there very early at the beginning of my CQRS/ES/DDD journey and is now here again to take over these modules.\n\nGolo Roden is the founder, CTO and managing director of [the native web](https://www.thenativeweb.io/), a company specializing in native web technologies. Among other things, he also teaches CQRS/ES/DDD etc. and based on his vast knowledge, he brought wolkenkit to life.\n[wolkenkit](https://wolkenkit.io) is a CQRS and event-sourcing framework based on Node.js. It empowers you to build and run scalable distributed web and cloud services that process and store streams of domain events.\n\nWith this step, I can focus more on [i18next](https://www.i18next.com), [locize](https://locize.com) and [localistars](https://localistars.com). I'm happy about that. 😊\n\nSo, there is no end, but the start of a new phase for my CQRS modules. 😉\n\nI wish you all good luck on your journey.\n\nWho knows, maybe we'll meet again in a github issue or PR at [i18next](https://github.com/i18next/i18next) 😉\n\n\n[Adriano Raiano](https://twitter.com/adrirai)\n\n---\n\n# Introduction\n\n[![travis](https://img.shields.io/travis/adrai/node-viewmodel.svg)](https://travis-ci.org/adrai/node-viewmodel) [![npm](https://img.shields.io/npm/v/viewmodel.svg)](https://npmjs.org/package/viewmodel)\n\nNode-viewmodel is a node.js module for multiple databases.\nIt can be very useful if you work with (d)ddd, cqrs, eventdenormalizer, host, etc.\n\n# Installation\n\n    $ npm install viewmodel\n\n# Usage\n\n## Connecting to an in-memory repository in read mode\n\n\tvar viewmodel = require('viewmodel');\n\n\tviewmodel.read(function(err, repository) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n    });\n\n## Connecting to any repository (mongodb in the example / mode=write)\nMake shure you have installed the required driver, in this example run: 'npm install mongodb'.\n\n    var viewmodel = require('viewmodel');\n\n    viewmodel.write(\n        {\n            type: 'mongodb',\n            host: 'localhost',      // optional\n            port: 27017,            // optional\n            dbName: 'viewmodel',    // optional\n            timeout: 10000          // optional\n            // authSource: 'authedicationDatabase',        // optional\n      \t    // username: 'technicalDbUser',                // optional\n      \t    // password: 'secret'                          // optional\n            // url: 'mongodb://user:pass@host:port/db?opts // optional\n        },\n        function(err, repository) {\n            if(err) {\n                console.log('ohhh :-(');\n                return;\n            }\n        }\n    );\n\n## Catch connect ad disconnect events\n\n    var repository = viewmodel.write({ type: 'mongodb' });\n    repository.on('connect', function() {\n        console.log('hello from event');\n    });\n    repository.on('disconnect', function() {\n        console.log('bye');\n    });\n    repository.connect();\n\n## Define a collection...\n\n    var dummyRepo = repository.extend({\n        collectionName: 'dummy'\n    });\n\n## Create a new viewmodel (only in write mode)\n\n    dummyRepo.get(function(err, vm) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n\n        vm.set('myProp', 'myValue');\n        vm.set('myProp.deep', 'myValueDeep');\n\n        console.log(vm.toJSON());\n\n        console.log(vm.has('myProp.deep'));\n\n        dummyRepo.commit(vm, function(err) {\n        });\n        // or you can call commit directly on vm...\n        vm.commit(function(err) {\n        });\n    });\n\n## Find...\n\n    // the query object ist like in mongoDb...\n    dummyRepo.find({ color: 'green' }, function(err, vms) {\n    // or\n    //dummyRepo.find({ 'deep.prop': 'dark' }, function(err, vms) {\n    // or\n    //dummyRepo.find({ age: { $gte: 10, $lte: 20 } }, function(err, vms) {\n    // or\n    //dummyRepo.find({ $or: [{age: 18}, {special: true}] }, function(err, vms) {\n    // or\n    //dummyRepo.find({ age: { $in: [1, 2, 3, 6] } }, function(err, vms) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n\n        // vms is an array of all what is in the repository\n        var firstItem = vms[0];\n        console.log('the id: ' + firstItem.id);\n        console.log('the saved value: ' + firstItem.get('color'));\n    });\n\n## Find with query options\n\n    // the query object ist like in mongoDb...\n    dummyRepo.find({ color: 'green' }, { limit: 2, skip: 1, sort: { age: 1 } }, function(err, vms) {\n    // or\n    //dummyRepo.find({ color: 'green' }, { limit: 2, skip: 1, sort: [['age', 'desc']] }, function(err, vms) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n\n        // vms is an array of all what is in the repository\n        var firstItem = vms[0];\n        console.log('the id: ' + firstItem.id);\n        console.log('the saved value: ' + firstItem.get('color'));\n    });\n\n## FindOne\n\n    // the query object ist like in mongoDb...\n    dummyRepo.findOne({ color: 'green' }, function(err, vm) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n\n        console.log('the id: ' + vm.id);\n        if (vm.has('color')) {\n            console.log('the saved value: ' + vm.get('color'));\n        }\n    });\n\n## Find by id...\n\n    // the query object ist like in mongoDb...\n    dummyRepo.get('myId', function(err, vm) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n\n        console.log('the id: ' + vm.id);\n        console.log('the saved value: ' + vm.get('color'));\n    });\n\n## Delete a viewmodel (only in write mode)\n\n    dummyRepo.get('myId', function(err, vm) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n\n        vm.destroy();\n\n        dummyRepo.commit(vm, function(err) {\n        });\n        // or you can call commit directly on vm...\n        vm.commit(function(err) {\n        });\n    });\n\n## Obtain a new id\n\n    myQueue.getNewId(function(err, newId) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n\n        console.log('the new id is: ' + newId);\n    });\n\n## Clear a \"collection\" (only in write mode)\n\n    dummyRepo.clear(function(err) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n    });\n\n## Catch before and after database events\n\n    var repository = viewmodel.write({ type: 'mongodb' });\n    repository.on('before-database-get', function(ms, id) { console.log(ms, id); });\n    repository.on('after-database-get', function(ms, id) { console.log(ms, id); });\n    repository.on('before-database-find', function(ms, query, queryOptions) { console.log(ms, query, queryOptions); });\n    repository.on('after-database-find', function(ms, query, queryOptions) { console.log(ms, query, queryOptions); });\n    repository.on('before-database-findOne', function(ms, query, queryOptions) { console.log(ms, query, queryOptions); });\n    repository.on('after-database-findOne', function(ms, query, queryOptions) { console.log(ms, query, queryOptions); });\n    repository.on('before-database-commit', function(ms, vm) { console.log(ms, vm); });\n    repository.on('after-database-commit', function(ms, vm) { console.log(ms, vm); });\n    \n\n# Implementation differences\n\n## Some implementations support bulkCommit\n\n    dummyRepo.bulkCommit([vm1, vm2, vm3], function(err) {\n        if(err) {\n            console.log('ohhh :-(');\n            return;\n        }\n    });\n\ncurrently supported by:\n- inmemory\n- mongodb\n- elasticsearch6\n\n\n## mongodb\nFor mongodb you can define indexes for performance boosts in find function.\n\n    var dummyRepo = repository.extend({\n        collectionName: 'dummy',\n        // like that\n        indexes: [\n            'profileId',\n            // or:\n            { profileId: 1 },\n            // or:\n            { index: {profileId: 1}, options: {} }\n        ]\n        // or like that\n        repositorySettings : {\n            mongodb: {\n                indexes: [ // same as above\n                    'profileId',\n                    // or:\n                    { profileId: 1 },\n                    // or:\n                    { index: {profileId: 1}, options: {} }\n                ]\n            }\n        }\n    });\n\n## redis\nThe find function does ignore the query argument and always fetches all items in the collection.\n\n## Elasticsearch \u003e= 5.X\nUse the 'elasticsearch6' type for Elasticsearch versions 5.X and 6.X.\n\nThe find queries are not mongoDb compatible as the rest of the implementations due to the uneeded overhead and complexity of converting between both formats.\n\nFor find queries with elasticsearch6 use elasticsearch [native elastic Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html);\n\nrepository.find( onlyTheQueryClause, otherBodyOptions, callback);\n\n```javascript\n    repository.find(\n        {\n            range : {\n                age : {\n                    gte : 10,\n                    lte : 20\n                }\n            }\n        ),\n        {\n            from: 0,\n            size: 10,\n            sort: { age: 'asc' }\n        },\n        function(error, results) {\n        });\n```\n\nAdditionaly for elasticsearch6 the number of shards, number of replicas, the refresh behaivour on index and the mappings on index create can be addtionaly defined to optimize performace.\n\n```javascript\n    var dummyRepo = repository.extend({\n        collectionName: 'dummy',\n        repositorySettings: {\n            elasticsearch6: {\n                refresh: 'wait_for', // optional, refresh behaviour on index, default is true ( ie. force index refresh ) https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-refresh.html                \n                waitForActiveShards: 2 // optional, defaults to 1 ( ie. wait only for primary ) https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html#create-index-wait-for-active-shards\n                index: { // optional applied on index create, https://www.elastic.co/guide/en/elasticsearch/reference/6.x/indices-create-index.html\n                    settings : { // will be merged with the default ones,\n                        number_of_shards: 3, // optional defaults to 1,\n                        number_of_replicas: 1 // optional defaults to 0,\n                    },\n                    mappings : { // optiona will be merged with the default ones,\n                        properties: { // specific properties to not be handled by dynamic mapper\n                            title: {\n                                type: \"text\"\n                            }\n                        }                    \n                    }\n                }\n            }\n        }\n    });\n```\n\n\n# [Release notes](https://github.com/adrai/node-viewmodel/blob/master/releasenotes.md)\n\n# Database Support\nCurrently these databases are supported:\n\n1. inmemory\n2. mongodb ([node-mongodb-native] (https://github.com/mongodb/node-mongodb-native))\n3. couchdb ([cradle] (https://github.com/cloudhead/cradle))\n4. tingodb ([tingodb] (https://github.com/sergeyksv/tingodb))\n5. redis ([redis] (https://github.com/mranney/node_redis))\n6. azuretable ([azure-storage](https://github.com/Azure/azure-storage-node))\n7. documentdb ([documentdb](https://github.com/Azure/azure-documentdb-node), [doqmentdb](https://github.com/a8m/doqmentdb))\n8. elasticsearch ([elasticsearch] (https://github.com/elastic/elasticsearch-js))\n9. elasticsearch6 ([elasticsearch] (https://github.com/elastic/elasticsearch-js)) - for Elasticsearch 5.x and 6.x\n10. dynamodb ([aws-sdk] (https://github.com/aws/aws-sdk-js))\n\n## own db implementation\nYou can use your own db implementation by extending this...\n\n    var Repository = require('viewmodel').Repository,\n    util = require('util'),\n        _ = require('lodash');\n\n    function MyDB(options) {\n      Repository.call(this, options);\n    }\n\n    util.inherits(MyDB, Repository);\n\n    _.extend(MyDB.prototype, {\n\n      ...\n\n    });\n\n    module.exports = MyDB;\n\n\n# License\n\nCopyright (c) 2019 Adriano Raiano\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthenativeweb%2Fnode-viewmodel","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthenativeweb%2Fnode-viewmodel","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthenativeweb%2Fnode-viewmodel/lists"}