我有一些代码可以从 mongo 数据库获取一些数据。
express app.get 中的函数将显示在浏览器 URL 中,但在此代码中,结果仅出现在控制台中,而不是出现在网页中,正如它应该的那样。
这是代码:
async function showdb() {
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db('mydb');
dbo.collection('test').findOne({}, function(err, result) {
if (err) throw err;
console.log(result);
return result;
// res.send(result); // commented out
// db.close(); // commented out
});
});
}
现在的路线:
app.get('/', (req, res) => {
showdb().then(result => {
res.send(result); // result is showing in the console
})
})
res.send(result);
应该在浏览器中显示数据,但它在控制台中显示。
我该如何解决这个问题?
最佳答案
两者MongoClient.connect()和 collection.findOne() 函数返回一个 Promise,因此您可以使用更少的代码链接它们,而无需使用回调:
function showdb() {
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
return MongoClient.connect(url, { useNewUrlParser: true })
.then((db) => {
return db.db('mydb').collection('test').findOne({});
});
}
现在 showdb
函数将向您的路由返回一个 Promise。
关于node.js - Node/express 异步函数 res.send 出现在控制台而不是页面中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387292/