【问题标题】:Data not getting pass on MongoDB collection [duplicate]数据未通过 MongoDB 集合 [重复]
【发布时间】:2019-09-13 13:53:11
【问题描述】:

您好,我正在尝试执行一个小型应用程序以将一组数据传递给 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');

  });
});

我得到的错误很少是 (index):87 POST http://localhost:3000/ 500 (Internal Server Error)GET http://localhost:3000/undefined 404 (Not Found)

我是 mongodb 传递数据的新手。

编辑:- 错误

终端错误:-

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)

【问题讨论】:

  • 请同时发布错误堆栈。
  • @DEVCNN 对不起,什么是错误堆栈?
  • 您在终端或浏览器控制台中遇到的错误。
  • @DEVCNN 我已经在我的问题检查中发布了:- (index):87 POST http://localhost:3000/GET http://localhost:3000/undefined 404 (Not Found) 在索引文件 xmlhttp.send(JSON.stringify(filteredFavMovies));
  • 你从哪里得到这些错误?发布截图。如果错误出现在终端中,请张贴截图。如果错误出现在浏览器中,请按 F12 打开控制台并发布屏幕截图。

标签: javascript node.js mongodb


【解决方案1】:

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

【讨论】:

  • 遇到同样的错误。如何检查数据是否从我的前端传递?如您所见,正在控制台上创建一个数组。我在文档中传递该数组。
  • 由于同样的错误,您是否仍然收到 db.collection is not a function 或其他错误,另一个错误 404?
  • 在路由 app.use((req, res, next) =&gt; { console.log(req.url); next() } ) 之前和你的路由 console.log(req.body) 开始时安装它
  • 我已将{ useNewUrlParser: true } 包含在MongoClient.connect 上,现在没有500 服务器错误,但数据未传入mongodb。我可以在文档中传递一个 Array[] 吗?
  • 只需将所有代码放在回调中即可。
【解决方案2】:

试试这个:

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连接函数之外(到文件末尾)

【讨论】:

  • 不,还没有通过
  • 你还有错误吗?
  • 是的,与提到的错误相同。
猜你喜欢
  • 2012-03-05
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多