Skip to content

Instantly share code, notes, and snippets.

@Darkborderman
Last active May 20, 2018 04:46
Show Gist options
  • Save Darkborderman/98118023428e8f095f8fc1040e83bd6f to your computer and use it in GitHub Desktop.
Save Darkborderman/98118023428e8f095f8fc1040e83bd6f to your computer and use it in GitHub Desktop.
Basic MongoDB 3.X operation using javascript.
let MongoClient=require('mongodb').MongoClient;
let userName="name";
let userPassword="password";
let serverHost="localhost";
let serverPort=27017;
let databaseURL=`mongodb://${userName}:${userPassword}@${serverHost}:${serverPort}`;
let databaseName="test";
let databaseCollection="test";
//about to insert data
MongoClient.connect(databaseURL,function(err,client) {
if(err) throw err;
else{
let currentDatabase=client.db(databaseName);
let currentCollection=currentDatabase.collection(databaseCollection);
let insertData={
name:"test",
address: "this is a test"
};
currentCollection.insertOne(insertData,function(err,res) {
if(err) throw err;
else console.log("1 document inserted");
client.close();
});
}
});
//about to find data in database
MongoClient.connect(databaseURL, function(err, client) {
if(err) throw err;
else{
let currentDatabase=client.db(databaseName);
let currentCollection=currentDatabase.collection(databaseCollection);
currentCollection.find({}).toArray(function(err,result){
if (err) throw err;
else console.log(result);
client.close();
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment