|
const chalk = require('chalk'); |
|
const Mongo = require('mongodb'); |
|
|
|
const MongoClient = Mongo.MongoClient; |
|
const MONGODB_URI = "mongodb://127.0.0.1:27017/lhl-tasks"; |
|
|
|
const statusChalker = { |
|
pending: chalk.bold.red, |
|
complete: chalk.bold.green |
|
} |
|
|
|
function showTasks(mongoInstance) { |
|
return new Promise(function (resolve, reject) { |
|
mongoInstance.collection("tasks").find({}).toArray(function (err, tasks) { |
|
if (err) { |
|
console.log(chalt.red(err)); |
|
return reject(err); |
|
} |
|
|
|
console.log(tasks.length + ' tasks'); |
|
|
|
tasks.forEach(function (task) { |
|
console.log(task._id + ': ' + statusChalker[task.status](task.title)); |
|
}); |
|
|
|
return resolve(); |
|
}); |
|
}); |
|
} |
|
|
|
function addTask(mongoInstance, title) { |
|
return new Promise(function (resolve, reject) { |
|
mongoInstance.collection("tasks").insertOne({ |
|
title: title, |
|
status: 'pending' |
|
}, function (err, result) { |
|
if (err) { |
|
console.log(chalt.red(err)); |
|
return reject(); |
|
} |
|
|
|
return resolve(); |
|
}); |
|
}); |
|
} |
|
|
|
function removeTask(mongoInstance, _id) { |
|
return new Promise(function (resolve, reject) { |
|
mongoInstance.collection("tasks").deleteOne({ |
|
_id: Mongo.ObjectID(_id) |
|
}, function (err, result) { |
|
if (err) { |
|
console.log(chalt.red(err)); |
|
return reject(); |
|
} |
|
|
|
return resolve(); |
|
}); |
|
}); |
|
} |
|
|
|
MongoClient.connect(MONGODB_URI, (err, mongoInstance) => { |
|
if (err) { |
|
throw err; |
|
} |
|
|
|
console.log(`Connected to MongoDb: ${MONGODB_URI}`); |
|
|
|
showTasks(mongoInstance) |
|
.then(function () { |
|
return addTask(mongoInstance, 'Item at ' + new Date().toTimeString()) |
|
}) |
|
.then(function () { |
|
return showTasks(mongoInstance); |
|
}) |
|
.then(function () { |
|
return removeTask(mongoInstance, '5b05c566c71b2a20785bf5ec'); |
|
}).then(function () { |
|
mongoInstance.close(); |
|
process.exit(); |
|
return |
|
}); |
|
}); |