使用MongoDB,Node.js和Express返回数据库信息时出现问题

时间:2019-06-04 18:17:04

标签: node.js mongodb

const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myorders';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("The connection was awesome");

  const db = client.db(dbName);
  second.get('/Students',(req,res) => {
  const findStudents = function(db,call) {
  const collection = db.collection('Students');
    collection.find({}).toArray(function (err,result) {
     if (!err) {
       res.send(result)
     } else {
         console.log(err);
         call(err);
     }
});
}
});
client.close();
});
second.listen(3200,() => {
  console.log('We got it running');
});
module.exports = second;

所以我试图在网络服务器上显示我的mongodb信息,这是屏幕截图

enter image description here

以上是MongoDB学生和成绩单的集合 enter image description here

上面是我的Node.js命令提示符,我收到了弃用警告。有什么办法可以解决?为什么我不能在Web服务器上显示信息还有其他错误?

1 个答案:

答案 0 :(得分:0)

要解决此弃用警告,您需要做的就是将其内容:将options对象中的选项useNewUrlParse: true传递给MongoClient.connect。因此,连接到MongoDB数据库的行将是:

MongoClient.connect(url, { useNewUrlParse: true }, function(err, client)

无论如何,这仅是警告,而不是阻止错误,并且您的应用程序正在运行。我认为您的代码中存在几处错误,主要是您在要与数据库的连接的回调中向/ Students声明要在GET上执行的函数,并且关闭了该连接,从而无法再访问数据。我认为这段代码应该对您有用:

const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbUrl = 'mongodb://localhost:27017';
const dbName = 'myorders';
let db;

MongoClient.connect(url, (err, client) => {
    assert.equal(null, err);
    db = client.db(dbName);
    console.log("The connection was awesome");
});

second.listen(3200, () => {
    console.log('We got it running');
});


second.get('/Students', (req, res) => {
    db.collection('Students').find().toArray((err,result) => {
        if (!err) {
            res.send(result)
        } else {
            console.log(err);
            res.status(500).send(err);
        }
    });
});

编辑:

如果您认为不应始终打开数据库,则应按以下方式在对/学生的每个请求中进行连接和关闭:

second.listen(3200, () => {
    console.log('We got it running');
});


second.get('/Students', (req, res) => {
    MongoClient.connect(url, (err, client) => {
        if (err) return res.status(500).send(err);

        db = client.db(dbName);
        db.collection('Students').find().toArray((err,result) => {
            if (!err) {
                res.send(result)
            } else {
                console.log(err);
                res.status(500).send(err);
            }
            client.close();
        });
    });
});