数据未通过MongoDB收集

时间:2019-04-24 09:47:53

标签: javascript node.js mongodb

您好,我正在尝试执行一个小型应用程序,以将数据数组传递给Mongodb,但是它没有传递。

我包括我的索引前端部分。

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>

我的 app.js节点文件。

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');

  });
});

我遇到的一些错误是(索引):87 POST http://localhost:3000/ 500(内部服务器错误) GET http://localhost:3000/undefined 404(未找到)< / strong>

我是mongodb传递数据的新手。

编辑:-错误

console error in browser

终端错误:-

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)

2 个答案:

答案 0 :(得分:2)

来自更新的MongoClient连接器的

mongodb不返回database参考。它会返回client

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);
   }
 });

然后在您的路线上

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');
  });
});

答案 1 :(得分:0)

尝试一下:

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

还将app.listen(3000);移至mongodb connect函数之外(移至文件末尾)