前提・実現したいこと
現在node.jsの勉強中です。
あまりこういった非同期の言語を触ってこなかったので悪戦苦闘しています。
今回お聞きしたいのでnode.jsでexpressとmongoDBを使ってプログラムを組みたいのですが
メインとなるapp.jsとmongoDBを処理するmng.jsに分けたいと考えて2ファイル作りました。
最初に1ファイルで処理を書いていた際はうまくいっていたのですが
ファイルを分け、別ファンクションにしたところ、
処理がうまく通らなくなりました。
原因を調べてみたところ、mng.connectdbの中でclientが取得出来る前に
mng.get_collectionが走ってしまい、client内がnullなのでエラーが起こっておりました。
この際の適切な書き方がありましたらご教授願いたいです。
mng.connectdbの前にawaitを付けても、nodejsから違うと怒られてしまいました。。。
(await is only valid in async functionと出ます)
該当のソースコード
### app.js const express = require('express'); const app = express(); const bodyParser = require('body-parser'); require('date-utils'); const mng = require('./mng'); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.get('/', (req, res) => { mng.connectdb("mongodb://localhost:27017", "nodetest"); mng.get_collection("nodetest"); mng.closedb(); res.status(200).send("ok").end(); }); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); console.log('Press Ctrl+C to quit.'); }); // その他のリクエストに対する404エラー app.use((req, res) => { res.sendStatus(404); }); module.exports = app;
### mng.js const MongoClient = require("mongodb").MongoClient; let client = null; let db = null; let cl = null; exports.connectdb = async function(url, dbName) { client = await MongoClient.connect(url, {useNewUrlParser: true, useUnifiedTopology: true}); trace("client:"+client); db = client.db(dbName); trace("db:"+db); } exports.closedb = function() { trace("closedb:"+db); if (client == null) return; client.close(); client = null; db = null; } exports.get_collection = function(collectionName) { trace("DB:"+db); if (db == null) return; cl = db.collection(collectionName); trace("Collection:"+cl); } function trace(str) { console.log(str); }
補足情報(FW/ツールのバージョンなど)
nodejs v10.16.3
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/10/09 01:27