shopping cart software as service samples nodejs code example

Example: how to craete a shopping cart in node js

// run this as nod.js
var http = require('http');
var url = require('url');
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    var urlQuery = url.parse(req.url, true).query;
    addItem(urlQuery.itemToAdd);
    removeItem(urlQuery.itemToRemove);
    res.end();
}).listen(8080);



function removeItem(remove) {
    if (remove !== undefined) {
        MongoClient.connect(mongourl, function (err, db) {
            if (err) throw err;
            var dbo = db.db("mydb");
            var myquery = { itemName: remove };
            dbo.collection("shoppingCart").deleteOne(myquery, function (err, obj) {
                if (err) throw err;
                console.log("deleted:" + myquery);
                db.close();
            });
        });
    }
}

function addItem(create) {
    if (create !== undefined) {
        MongoClient.connect(mongourl, function (err, db) {
            if (err) throw err;
            var dbo = db.db("mydb");
            var myobj = { itemName: create };
            dbo.collection("shoppingCart").insertOne(myobj, function (err, res) {
                if (err) throw err;
                console.log("document inserted:" + myobj);
                db.close();
            });
        });
    }
}