【问题标题】:How to fetch data in mongoDB to show in localhost (Node.js)如何在 mongoDB 中获取数据以显示在 localhost (Node.js)
【发布时间】:2017-07-13 06:05:10
【问题描述】:

我正在使用 mongoDB 和 node.js 做列表应用程序。基本上你输入你想要做的然后点击添加。我成功连接了数据库,但它没有显示数据库中的文本。它仅显示 localhost 中的项目符号。

代码如下:

app.get('/', function(req, res) {
  db.collection('list').find().toArray(function (err, result) {
    console.log(result);
    if (err) {return};
    console.log(err);
res.render('index.ejs', {list: result})
 });
});

app.post('/', function(req, res){
 console.log(req.body);
  db.collection('list').save(req.body, function(err, result) {
  if (err) {return};
  console.log(err);

  console.log('saved')
  res.redirect('/');
 })
})

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    我已经验证了您发布的代码,并使用 cmets 对其进行了轻微修改。 我希望这会有所帮助,但似乎错误可能出在正在使用的 res.render 方法中。请参考以下代码:

    // Requires
    var express = require('express');
    var bodyParser = require('body-parser');
    var MongoClient = require('mongodb').MongoClient;
    // Instantiation
    var app = express();
    var mongopath = "mongodb://localhost:27017/BitX";
    // Port number the REST api works on
    var portnum = 7500;
    // MongoDB object
    var db = null;
    MongoClient.connect(mongopath, function(err,ldb){
      db = ldb;
    });
    
    // Implement Body Parser
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    
    // Start the REST service
    var server = app.listen(portnum, function() {
        var host = server.address().address;
        var port = server.address().port;
        console.log("Content Provider Service listening at http://%s:%s", host, port);
    });
    
    // Default route
    app.get('/', function(req, res) {
      // Find all items in orders and send back results to a front end
      db.collection('orders').find().toArray(function (err, result) {
        res.send(result);
        // Consider that the rendering engine may not be functioning correctly
        // SEE MORE: https://stackoverflow.com/questions/21843840/what-does-res-render-do-and-what-does-the-html-file-look-like
        //res.render('index.ejs', {list: result})
     });
    });
    
    // Accept a post on the root
    app.post('/', function(req, res){
      //Save into orders
      db.collection('orders').save(req.body, function(err, result) {
        res.send(true);
        //res.redirect('/');
      });
    });
    

    有关 res.render 方法的更多信息,请查看: What does "res.render" do, and what does the html file look like? - 如果你还没有。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 2018-06-17
      相关资源
      最近更新 更多