0

Hello I am trying to execute a small application to pass an array of data to Mongodb but ,it is not getting pass .

I am including my index front-end portion.

function addListItem(title, listId) {
  var ul = document.getElementById(listId);
  var li = document.createElement("li");
  li.className = 'list-group-item';
  li.appendChild(document.createTextNode(title));
  ul.appendChild(li);
}

let results;

function afterLoad() {
    var data = JSON.parse(this.responseText);
    var name = document.createElement('img');
    
    results = data.results;
     
    // loop through items
    results.forEach(item => {
      addListItem(item.title, "items");
    });
    
    name.src = data.title;
    document.body.appendChild(name);
}

function afterClick() {
    // changed target to focus search
    var terms = document.getElementById("search").value.split(' ').join('+');
    var request = new XMLHttpRequest();
    request.addEventListener('load', afterLoad);
    request.open('GET', 'https://api.themoviedb.org/3/search/movie?api_key=8318c431b4fc8a2c4762bf2a52c351ee&query='+terms);
    request.send();
}

button.addEventListener("click", afterClick);

const submitBtn = document.querySelector('input[value="Submit"]');
const favMovie = document.querySelector('form > input');

submitBtn.addEventListener('click', function(e) {
    e.preventDefault();
    const favMovieName = favMovie.value;
    if(favMovieName.length > 0) {
        const filteredFavMovies = results.filter(({title}) => title.toLowerCase().includes(favMovieName.toLowerCase()));
        console.log(filteredFavMovies);
        
        //passing data to mongodb
        var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
  xmlhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
      document.getElementById("result").innerHTML =
      this.responseText;
   }
   };
  xmlhttp.open("POST", "http://localhost:3000");
  xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xmlhttp.send(JSON.stringify(filteredFavMovies));
    }
});
<header id="main-header" class="bg-success text-white p-4 mb-3">
    <div class="container">
        <h1 id="header-title">Get Movies<span style="display:none">123</span></h1>
        <input style="align:right" type="text" class="form-control mr-2" id="search">
        <input type="submit" class="btn btn-dark" value="Search" id="button">
    </div>
</header>
<div class="container">
    <div id="main" class="card card-body">
        <h2 class="title">Add Fav Movies</h2>
        <form class="form-inline mb-3">
            <input type="text" class="form-control mr-2">
            <input type="submit" class="btn btn-dark" value="Submit">
            <p id ="result"></p>
        </form>
        <h2 class="title">Lists</h2>
        <ul id="items" class="list-group">

        </ul>
    </div>
</div>

My app.js node file.

var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

var db;

//Establish Connection
MongoClient.connect('mongodb://localhost:27017/myproject', function (err, database) {
   if (err) 
    throw err
   else
   {
    db = database;
    console.log('Connected to MongoDB');
    //Start app only after connection is ready
    app.listen(3000);
   }
 });

app.use(bodyParser.json())

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});

app.post('/', function(req, res) {
   // Insert JSON straight into MongoDB
  db.collection('documents').insert(req.body, function (err, result) {
      if (err)
         res.send('Error');
      else
        res.send('Success');

  });
});

Few errors which I am getting is (index):87 POST http://localhost:3000/ 500 (Internal Server Error) and GET http://localhost:3000/undefined 404 (Not Found)

I am new in mongodb passing data.

EDIT :- error

console error in browser

error in terminal:-

TypeError: db.collection is not a function
    at C:\Users\india\Desktop\myproject\app.js:31:6
    at Layer.handle [as handle_request] (C:\Users\india\Desktop\myproject\node_m
odules\express\lib\router\layer.js:95:5)
    at next (C:\Users\india\Desktop\myproject\node_modules\express\lib\router\ro
ute.js:137:13)
    at Route.dispatch (C:\Users\india\Desktop\myproject\node_modules\express\lib
\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\india\Desktop\myproject\node_m
odules\express\lib\router\layer.js:95:5)
    at C:\Users\india\Desktop\myproject\node_modules\express\lib\router\index.js
:281:22
    at Function.process_params (C:\Users\india\Desktop\myproject\node_modules\ex
press\lib\router\index.js:335:12)
    at next (C:\Users\india\Desktop\myproject\node_modules\express\lib\router\in
dex.js:275:10)
    at C:\Users\india\Desktop\myproject\node_modules\body-parser\lib\read.js:130
:5
    at invokeCallback (C:\Users\india\Desktop\myproject\node_modules\raw-body\in
dex.js:224:16)
NoobCoder
  • 493
  • 8
  • 25
  • Please post the error stack as well. – DEVCNN Apr 24 '19 at 09:53
  • @DEVCNN Pardon , what is error stack ? – NoobCoder Apr 24 '19 at 09:57
  • The errors that you are getting in the terminal or the browser console. – DEVCNN Apr 24 '19 at 10:01
  • @DEVCNN I have posted in my question check :- `(index):87 POST http://localhost:3000/` and `GET http://localhost:3000/undefined 404 (Not Found)` at index file `xmlhttp.send(JSON.stringify(filteredFavMovies));` – NoobCoder Apr 24 '19 at 10:05
  • where have you got these errors? Post a screenshot. If the errors are in terminal post a screenshot of that. If the errors are in the browser, open console by pressing F12 and post a screenshot of that. – DEVCNN Apr 24 '19 at 10:09
  • @DEVCNN At terminal I am getting this error `TypeError: db.collection is not a function` and for console I am attaching image in EDIT:- – NoobCoder Apr 24 '19 at 10:13
  • @1556089774 I had already. – NoobCoder Apr 24 '19 at 10:16

2 Answers2

2

MongoClient from updated mongodb connector does not return database reference. It returns client instead.

let connection;
//Establish Connection

MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, function (err, client) {
   if (err) 
    throw err
   else {
    connection = client;
    console.log('Connected to MongoDB');
    //Start app only after connection is ready
    app.listen(3000);
   }
 });

Then in your route:

app.post('/', function(req, res) {
  // Insert JSON straight into MongoDB
  connection.db('myproject').collection('documents').insert(req.body, function (err, result) {
    if (err)
      res.send('Error');
    else
      res.send('Success');
  });
});
1565986223
  • 6,420
  • 2
  • 20
  • 33
  • Getting same error. How can I check if the data is passing from my front-end or not ? As you can see an array is being created on console. I am passing that array in document. – NoobCoder Apr 24 '19 at 10:28
  • By same error are you still getting `db.collection is not a function` or something else, the other error 404? – 1565986223 Apr 24 '19 at 10:29
  • mount this before routes `app.use((req, res, next) => { console.log(req.url); next() } )` and in your route `console.log(req.body)` at the start – 1565986223 Apr 24 '19 at 10:31
  • I have included `{ useNewUrlParser: true }` on `MongoClient.connect` and now there is no 500 server error , but data is not passed in mongodb. Can I pass an Array[ ] in document ? – NoobCoder Apr 24 '19 at 10:33
  • 1
    Just put all the code inside the callback. – DEVCNN Apr 24 '19 at 10:34
  • `Can I pass an Array[ ] in document`, yes you can – 1565986223 Apr 24 '19 at 10:38
  • @1556089774 Including `app.use((req, res, next) => { console.log(req.url); next() } )` at first stopped my application. Not getting api response. – NoobCoder Apr 24 '19 at 10:38
  • ok it's working now after removing `app.use((req, res, next) => { console.log(req.url); next() } )`. Thanks – NoobCoder Apr 24 '19 at 10:40
  • yes after `app.use(bodyParser.json())` – NoobCoder Apr 24 '19 at 10:41
  • How, can I get in javascript the same documents details ? – NoobCoder Apr 24 '19 at 11:02
0

Give this a try:

app.post('/', function(req, res) {
db.collection('documents').insertOne({body: req.body}, function (err, result) {
  if (err)
     res.send('Error');
  else
     res.send('Success');
});
});

also move app.listen(3000); outside mongodb connect function (to the end of file)

Dorian Mazur
  • 514
  • 2
  • 12