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 信息,这里是屏幕截图
上面是我的 Node.js 命令提示符,我收到了弃用警告。有什么办法可以解决吗?是否还有其他错误,为什么我无法在 Web 服务器中显示信息?
要修复此弃用警告,您只需按照它说的做:将useNewUrlParse: true
选项对象中的选项传递给MongoClient.connect
. 因此,您连接到 MongoDB 数据库的行将是:
MongoClient.connect(url, { useNewUrlParse: true }, function(err, client)
无论如何,这只是一个警告,而不是一个阻塞错误,并且您的应用程序正在运行。我认为您的代码中有几处错误,主要是您在与数据库的连接的回调中将要在 GET 上执行的函数声明为 /Students 并关闭该连接以便无法再访问数据. 我认为这段代码应该适合你:
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);
}
});
});
编辑:
如果您认为不应该总是打开数据库,您应该在每次请求 /Students 时连接和关闭,如下所示:
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();
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句