Skip to content

Instantly share code, notes, and snippets.

@kanreisa kanreisa/mongodb.js
Last active May 18, 2016

Embed
What would you like to do?
"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
You can’t perform that action at this time.