Daniel Minnaar
Daniel Minnaar

Reputation: 6295

What are some patterns I can look at for database implementations in JavaScript?

I'm fairly new to JavaScript, and I'm busy playing around with a node test app and MongoDB.

I'm at a point where I'd like to start with the db side of the app, but I'm not sure what patterns are most commonly used in such a stack, and more importantly, why.

So far, I've got this:

var mongoClient = mongodb.MongoClient;
var mongoUrl = 'mongodb://localhost:27017/MyDB'

    function openConnection() {
        var database;
        mongoClient.connect(mongoUrl, function (err, db) {
            if (err) {
                return null;
            } else {
                database = db;
            }
        });
        return database;
    }

My initial idea was to have a connect() function, and execute requests for inserts / updates in the respective functions, something like:

function addPerson() {
   var db = openConnection();
   db.doInsert(myObject);
   db.close();
}

What are some of the preferred ways of accomplishing my example?

Also, on a side note, the openConnection() function always returns null, even though the database object in the mongoClient.connect works as expected. Does the 'db' object somehow lose context when out of the mongoClient.connect() function?

Upvotes: 0

Views: 330

Answers (1)

pid
pid

Reputation: 11597

That's a pretty wide question, partly opinion based. This question should be closed, but I still want to give you some advice.

There once was the Active Record pattern, which has been proven to be pretty difficult to maintain.

The solution was the DAO pattern, but this adds a lot of code if done right.

So, relatively recently (some 5-8 years ago, since Domain Driven Design enjoyed some wider audience) the Repository pattern is seen in many frameworks.

This pattern seems to fit very well with other patterns and technologies.

So, what I would recommend you to try, is this tutorial which should be pretty straight forward. Below the tutorial is a comment pointing to this github repository. It avoids coffee-script if you are not so inclined as is solely based on node.js/mongoDB and pure JS.

Upvotes: 2

Related Questions