Skip to content

Instantly share code, notes, and snippets.

@francisngo
Last active December 29, 2017 07:33
Show Gist options
  • Save francisngo/999a75b82b48fe76f8ba3435c48da97e to your computer and use it in GitHub Desktop.
Save francisngo/999a75b82b48fe76f8ba3435c48da97e to your computer and use it in GitHub Desktop.
Create MongoDB queries to insert a document into a collection and to find a document in a collection
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/test';
mongoClient.connect(url, function(err, db) {
if (err) {
throw err;
console.log('ERROR - Unable to connect to database.')
}
console.log('INFO - Database connected.');
db.createCollection('users', function(err, collection) {
if (err) {
throw err;
console.log('ERROR - Unable to create collection');
}
console.log('INFO - Collection created.');
let data = {
name: 'Francis Ngo',
password: 'password123',
admin: true
};
collection.insert(data, function(err, docs) {
if (err) {
throw err;
console.log('ERROR - Unable to insert data.');
}
console.log('INFO - Document inserted.');
collection.count(function(err, count) {
if (err) {
throw err;
console.log('ERROR - Unable to count documents');
}
console.log('INFO - The collection contains ' + count + ' documents.');
});
collection.find().toArray(function(err, documents) {
if (err) {
throw err;
console.log('ERROR - Unable to find document.');
}
documents.forEach(function(document) {
console.log('INFO - Found a document with name: ' + document.name);
});
db.close();
console.log('INFO - Database connection closed.')
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment