我有一個包含國家和相關城市的 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,因為使用了異步函式,并嘗試回傳該值,結果只是Promise { <pending> }在我嘗試訪問它時導致了server.js
然后我有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);
});
IE
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: []
}
所以這不是我想要的國家名單。
我想將其傳遞給我的哈巴狗檔案:index.pug作為我的下拉選擇串列的內容。
請注意,我是 javascript 和 mongodb 的菜鳥。
非常感謝您的幫助和指導。
uj5u.com熱心網友回復:
您無法從該函式本身范圍之外的異步函式獲取資料。您可以在 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
});
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/440580.html
標籤:javascript 节点.js mongodb 承诺
