Illuminatiiiiii
11/24/2018 - 1:44 AM

How to use MongoDB with Node.js

const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;

//URL to the mongo server
const url = "mongodb://localhost:27017";
 
MongoClient.connect(url, function(error, client){
    if(error){
        console.log("Problem connecting to server.");
    }else{
        console.log("Connected to server");

        //Connect to a database
        var humansDB = client.db("humans");

        //Connect to the people collection
        var peopleCollection = humansDB.collection("people");

        //Insert a document into the collection
        peopleCollection.insertOne({
            name: "Bobby",
            age: "500",
            weight: 130
        });

        //List all of the documents in the people collection
        var data = peopleCollection.find({}).toArray(function(error, data){
            if(error){
                console.log("Error getting data");
            }else{
                console.log(data);
            }
        });

        //Close the connection
        client.close();

    }
});

app.listen(3000, () => console.log('Listening on port 3000!'));