最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - MongoDB get data to display in HTML - Stack Overflow

programmeradmin1浏览0评论

I'm trying to display mongodb data in my html page. I've already managed to insert data in db but for some reason my "get" function does not work.

I'm using node.js with express framework and Angular for front-end and routing.

This is my "get" function to retreive data from MongoDB:

var mongo = require('mongodb');
var assert = require('assert');

var url = 'mongodb://localhost:27017/loodgieters';

router.get('/get-data', function(req, res, next) {
  var resultArray = [];
  mongo.connect(url, function(err, db){
    assert.equal(null, err);
    var cursor = db.collection('user-data').find();
    cursor.forEach(function(doc, err){
      assert.equal(null, err);
      resultArray.push(doc);
    }, function(){
      db.close();
      res.render('index', {items: resultArray});
    });
  });
});

And my "post" which works

router.post('/insert', function(req, res, next) {
  var item = {
    name: req.body.name,
    adress: req.body.adress,
    postal: req.body.postal,
    city: req.body.city,
    email: req.body.email,
    phone: req.body.phone,
    quotation: req.body.quotation,
    message: req.body.message
  };
  mongo.connect(url, function(err, db) {
    assert.equal(null, err);
    db.collection('user-data').insertOne(item, function(err, result){
      assert.equal(null, err);
      console.log('Item inserted');
      db.close();
    });
  });
  res.redirect('/contact');
});

I'm trying to display mongodb data in my html page. I've already managed to insert data in db but for some reason my "get" function does not work.

I'm using node.js with express framework and Angular for front-end and routing.

This is my "get" function to retreive data from MongoDB:

var mongo = require('mongodb');
var assert = require('assert');

var url = 'mongodb://localhost:27017/loodgieters';

router.get('/get-data', function(req, res, next) {
  var resultArray = [];
  mongo.connect(url, function(err, db){
    assert.equal(null, err);
    var cursor = db.collection('user-data').find();
    cursor.forEach(function(doc, err){
      assert.equal(null, err);
      resultArray.push(doc);
    }, function(){
      db.close();
      res.render('index', {items: resultArray});
    });
  });
});

And my "post" which works

router.post('/insert', function(req, res, next) {
  var item = {
    name: req.body.name,
    adress: req.body.adress,
    postal: req.body.postal,
    city: req.body.city,
    email: req.body.email,
    phone: req.body.phone,
    quotation: req.body.quotation,
    message: req.body.message
  };
  mongo.connect(url, function(err, db) {
    assert.equal(null, err);
    db.collection('user-data').insertOne(item, function(err, result){
      assert.equal(null, err);
      console.log('Item inserted');
      db.close();
    });
  });
  res.redirect('/contact');
});
Share Improve this question edited Apr 18, 2017 at 12:17 tanmay 7,9112 gold badges23 silver badges39 bronze badges asked Apr 18, 2017 at 12:16 LarsmansonLarsmanson 4131 gold badge6 silver badges20 bronze badges 3
  • Are you using the node-mongodb-native driver directly or do you use mongoose ? – Julien TASSIN Commented Apr 18, 2017 at 14:10
  • I'm using the node mongodb native. Not mongoose – Larsmanson Commented Apr 18, 2017 at 14:33
  • How it "doesn't work"? Any error is throwing? – Thevs Commented Apr 19, 2017 at 5:45
Add a ment  | 

4 Answers 4

Reset to default 1

i am not sure if this is the correct way to open and close mongo connection each time you are trying to query . if you want to go for another approach then use mongoose and follow something like this https://pastebin./g7aatzzj

I think that you have a mistake in your .find().forEach function callbacks. The error handling seems to be in the endCallback not the iteratorCallback.

According to the official doc, the correct way should be :

var mongo = require('mongodb');
var assert = require('assert');

var url = 'mongodb://localhost:27017/loodgieters';

router.get('/get-data', function(req, res, next) {
  var resultArray = [];
  mongo.connect(url, function(err, db){
    assert.equal(null, err);
    var cursor = db.collection('user-data').find({});
    cursor.forEach(function(doc){
      assert.notEqual(null, doc);
      resultArray.push(doc);
    }, function(err, doc){
      assert.equal(null, err);
      db.close();
      res.render('index', {items: resultArray});
    });
  });
});

This can also be found in their unit tests

    var cursor = collection.find({})
      .map(function(x) { return {a:1}; })
      .batchSize(5)
      .limit(10);
    cursor.forEach(function(doc) {
      test.equal(1, doc.a);
    }, function(err, doc) {
      test.equal(null, err);
      db.close();
      test.done();
    });

I think that you must have a error that is not passed to the first callback and not handled in the second one. So you do not see the error.

Try to insert an empty object to the find() function as following:

var cursor = db.collection('user-data').find({});

I have just run your code and modified it a bit for my purposes. Please find the following snippet

//Instantiate MongoClient
var mongo = require('mongodb').MongoClient;
//Assert library (Perhaps overkill if you are writing production-level code)
var assert = require('assert');
//Express engine
var express = require('express');

//URL for my mongo instance
//Connecting to the blog database
var url = 'mongodb://localhost:27017/blog';

//Instantiate express
var router = express();

//Get operation
router.get('/get', function(req, res, next) {
  var resultArray = [];
  mongo.connect(url, function(err, db){
    assert.equal(null, err);
    var cursor = db.collection('posts').find();
    cursor.forEach(function(doc, err){
      assert.equal(null, err);
      resultArray.push(doc);
    }, function(){
      db.close();
      //I have no index file to render, so I print the result to console
      //Also send back the JSON string bare through the channel
      console.log(resultArray);
      res.send(resultArray);
    });
  });
});

//Start listeninig
//Hardcoded port 1000
var server = router.listen(1000, function() {
    var host = server.address().address;
    var port = server.address().port;
    console.log("Content Provider Service listening at http://%s:%s", host, port);
});

Therefore to get this working for you:

  1. Change the url to 'mongodb://localhost:27017/loodgieters';
  2. Change router to '/get-data'

I hope this helps! Also consider using splitting the implementation of the get operation to another module to help for the Separation of Responsibilities to make your code more robust.

发布评论

评论列表(0)

  1. 暂无评论