Skip to content

Instantly share code, notes, and snippets.

@kanreisa
Last active May 18, 2016 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanreisa/5c338cb42530303aecd41f52fb569ff3 to your computer and use it in GitHub Desktop.
Save kanreisa/5c338cb42530303aecd41f52fb569ff3 to your computer and use it in GitHub Desktop.
"use strict";
const http = require("http");
const MongoClient = require('mongodb').MongoClient;
let collection = null;
let documentId = null;
MongoClient.connect("mongodb://user:pass@hostname:port/dbName", (err, db) => {
if (err) {
console.error(err);
process.exit();
return;
}
db.collection("test", (err, _collection) => {
collection = _collection;
collection.findOne()
.then(doc => {
if (doc) {
return Promise.resolve(doc);
} else {
return collection.insert({ count: 0 });
}
})
.then(doc => {
documentId = doc._id;
})
.catch(err => {
console.error(err);
});
});
});
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain");
res.writeHead(200);
if (!documentId) {
res.end("documentId is null. retry please.");
return;
}
let startAt = Date.now();
let readTime = -1;
let count = -1;
collection.findOne(documentId)
.then(doc => {
readTime = Date.now() - startAt;
++doc.count;
count = doc.count;
startAt = Date.now();
return collection.updateOne({ _id: documentId }, doc);
})
.then(() => {
res.end(`This is DocumentDB protocol support for MongoDB Read/Update Demo. -> count=${count} (r/w: ${readTime}/${Date.now() - startAt} ms)`);
})
.catch(err => {
console.error("error!", err);
res.end(JSON.stringify(err));
});
});
server.listen(process.env.PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment