mongodb将数据查询到html下拉菜单



我有一个mongo数据库,里面有国家及其关联城市。我想从数据库中提取国家,并将数据放在HTML下拉选择列表中。

我在mongodbActions.js中有以下内容用于连接到我的mongodb实例,并进行国家/地区的查询和返回。

const {MongoClient} = require('mongodb');
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
const Promise = require('rsvp').Promise;
// exporting functions
module.exports = {
mongodbConn: async function() {
try {
// Connect to the mongodb server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Successfully connected to mongo DB.");
} catch (e) {
console.error(e);
} finally {
await client.close();
console.log("Successfully closed connection to mongo DB.");
}
},
mongodbGetCountries: function() {
return new Promise(function(resolve, reject) {
const dbo = client.db('mydb').collection('countries_cities');
let dbCountries = dbo.distinct('country', function(err, dbCountries) {
if (err) {
reject(err);  
} else {
resolve(dbCountries);
}
});
});
},
};

我使用了Promises,就像使用异步函数一样,并试图返回值,但在我的server.js中尝试访问它时,只得到了Promise { <pending> }

然后我有server.js,它有内容:

// load the express module
const express = require('express');
// load boad-parser module
const bodyParser = require('body-parser');
const mongodbActions = require('./static/scripts/mongodbActions')
console.log(mongodbActions)
// init db connection
mongodbActions.mongodbConn()
// get countries from db
let dbCountries = mongodbActions.mongodbGetCountries().then(function (items) {
console.info('The promise was fulfilled with items!', items);
return items
}, function(err) {
console.error('The promise was rejected', err, err.stack);
});
console.log('server side countries:')
console.log(dbCountries)
const index = 'index.pug';
const app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.urlencoded({extended: true}))
app.use(express.static(__dirname+'/static'));
// index page
app.get('/', function (req, res) {
console.log(req.url);
// weather info / data -> display set to on
let weatherVisibilty = 'visibility_on';
let countryList = dbCountries
res.render(index, { 
countryList: countryList,
setVisibility: weatherVisibilty 
});
})

下面的代码块显示了列表中的国家/地区,就像我想要的那样。

// get countries from db
let dbCountries = mongodbActions.mongodbGetCountries().then(function (items) {
console.info('The promise was fulfilled with items!', items);
return items
}, function(err) {
console.error('The promise was rejected', err, err.stack);
});

The promise was fulfilled with items! [
'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR',
'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE',
'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ',
'BR', 'BS', 'BT', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF',
'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU',
'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO',
'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ',
'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG',
'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT',
'GU', 'GW', 'GY', 'HK', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE',
... 146 more items
]

然而,下面的块,我希望它是上面items的值。

console.log('server side countries:')
console.log(dbCountries)

返回以下内容:

server side countries:
Promise {
_id: 1,
_label: undefined,
_state: undefined,
_result: undefined,
_subscribers: []
}

所以这不是我想要的国家列表。

我想把它传递给我的pug文件:index.pug,作为我下拉选择列表的内容。

请注意,我对javascript和mongodb非常熟悉。

我们将非常感谢您的协助和指导。

不能从异步函数本身范围之外的异步函数获取数据。您可以在SO上阅读这个答案,以更好地了解异步调用是如何工作的。

这就是为什么console.log(dbCountries)总是回报承诺的原因。

我建议你使用async/await并修改你的GET路线

app.get('/', async (req, res) => {
console.log(req.url);
// weather info / data -> display set to on
let weatherVisibilty = 'visibility_on';
let dbCountries = await mongodbActions.mongodbGetCountries();
let countryList = dbCountries
res.render(index, { 
countryList: countryList,
setVisibility: weatherVisibilty 
});
})

最新更新