Skip to content

Instantly share code, notes, and snippets.

@wh1tew0lf
Last active May 19, 2018 18:59
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 wh1tew0lf/9fc3452c341232a8fc7c3eea38d0e383 to your computer and use it in GitHub Desktop.
Save wh1tew0lf/9fc3452c341232a8fc7c3eea38d0e383 to your computer and use it in GitHub Desktop.
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://mongo:27017/mydb";
const query = { address: "Highway 37" };
const myDoc = { name: "Company Inc", address: "Highway 37" };
const p = new Promise((resolve, reject) => {
MongoClient.connect(url, (err, db) => {
if (err) reject(err);
console.log("Database created!");
resolve(db);
});
});
p.then(db => {
return new Promise((resolve, reject) => {
const dbo = db.db("mydb");
dbo.createCollection("customers", function(err, res) {
if (err) reject(err);
console.log("Collection created!");
resolve(db);
});
})
})
.then(db => {
return new Promise((resolve, reject) => {
const dbo = db.db("mydb");
dbo
.collection("customers")
.insertOne(myDoc, function(err, res) {
if (err) reject(err);
console.log("1 document inserted");
resolve(db);
});
});
})
.then(db => {
return new Promise((resolve, reject) => {
const dbo = db.db("mydb");
dbo
.collection("customers")
.find(query)
.toArray(function(err, result) {
if (err) reject(err);
console.log('This is what we found:', result);
resolve(db);
});
});
})
.then(db => {
db.close();
})
.catch(error => {
console.error(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment