MongoDBインスタンスへの接続を確立するデータベースラッパークラスがあります:
async connect(connectionString: string): Promise<void> {
this.client = await MongoClient.connect(connectionString)
this.db = this.client.db()
}
という警告が表示されました:
(node:4833) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version.新しいパーサーを使うには、オプション { useNewUrlParser: true } を MongoClient.connect に渡します。
connect()メソッドは第二引数に
MongoClientOptionsインスタンスを受け取ります。しかし、これには
useNewUrlParserというプロパティがありません。これらのプロパティを接続文字列で次のように設定してみました:mongodb://127.0.0.1/my-db?useNewUrlParser=true
のように接続文字列でプロパティを設定してみましたが、警告には効果がありませんでした。
どうすれば useNewUrlParser
を設定して警告を消すことができるでしょうか?このスクリプトはcronとして実行する必要があり、これらの警告はトラッシュメールのスパムになるので、これは私にとって重要です。
私はバージョン 3.1.0-beta4
の mongodb
ドライバと 3.0.18
の @types/mongodb
パッケージを使っています。どちらも npm install
を使って入手できる最新のものです。
古いバージョンの mongodb ドライバを使っている:
"mongodb": "~3.0.8",
"@types/mongodb": "~3.0.18"
mongoのバージョンを確認する
mongo --version
バージョン >= 3.1.0 を使っている場合は、mongo の接続ファイルを ->;
MongoClient.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })
に変更してください;
mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true });
理想的にはバージョン4の機能ですが、v3.1.0以降でもサポートされています。詳しくは MongoDB Github を参照してください。
前述のように、ドライバの 3.1.0-beta4
リリースが少し早くリリースされた。このリリースは MongoDB 4.0 の新機能をサポートし、API を変更するための作業の一環です。
今回の警告の引き金となっている変更のひとつは useNewUrlParser
オプションです。これについては後で詳しく説明する。
物事が落ち着くまで、少なくとも 3.0.x
リリースのマイナーバージョンに "pin" することをお勧めします:
"dependencies": {
"mongodb": "~3.0.8"
}
これで 3.1.x
ブランチが "fresh" でノードモジュールにインストールされなくなるはずです。もし既に"beta"バージョンである"latest"リリースをインストールしたのであれば、パッケージをクリーンアップして(そしてpackage-lock.json
も)、そのリリースを3.0.x
シリーズまで落としてください。
実際に "new" 接続 URI オプションを使用する場合の主な制限は、接続文字列に port
を含めることです:
const { MongoClient } = require("mongodb");
const uri = 'mongodb://localhost:27017'; // mongodb://localhost - will fail
(async function() {
try {
const client = await MongoClient.connect(uri,{ useNewUrlParser: true });
// ... anything
client.close();
} catch(e) {
console.error(e)
}
})()
これは新しいコードではより厳格なルールです。現在のコードは基本的に "node-native-driver" ( npm mongodb
) リポジトリコードの一部であり、新しいコードでは "public" node ドライバを支える mongodb-core
ライブラリからインポートしています。
オプションが追加されたポイントは、新しいコードにオプションを追加することで移行を容易にし、オプションを追加するコードで新しいパーサ(実際にはurl
をベースにしています)が使用され、非推奨の警告をクリアすることで、渡された接続文字列が実際に新しいパーサが期待するものに適合していることを確認することです。
将来のリリースでは、'legacy'パーサーは削除され、新しいパーサーはオプションがなくても使われるようになるでしょう。しかし、その時までに、すべての既存のコードは、新しいパーサーが期待するものに対して既存の接続文字列をテストする十分な機会を得ていることが期待されます。
ですから、新しいドライバの機能がリリースされたときにそれを使い始めたいのであれば、利用可能な beta
リリースとそれ以降のリリースを使い、MongoClient.connect()
で useNewUrlParser
オプションを有効にすることで、新しいパーサでも有効な接続文字列を提供できるようにするのが理想的です。
MongoDB 4.0 リリースのプレビューに関連する機能にアクセスする必要がない場合は、前述のようにバージョンを 3.0.x
系に固定します。これはドキュメント通りに動作し、ピン留めすることで実際に安定版をインストールするまで 3.1.x
リリースが依存関係を超えて更新されることはありません。
マングース接続への強調表示されたコードの下で、マングースドライバーの警告が解決されました。
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
接続文字列形式は mongodb:// user:password@host:port / db でなければなりません。
例えば:
MongoClient.connect('mongodb://user:[email protected]:27017/yourDB', { useNewUrlParser: true } )
{useNewUrlParser:true}
を追加する必要はないと思います。
新しいURLパーサーをすでに使用する場合は、あなた次第です。 最終的に、モンゴが新しいURLパーサーに切り替わると警告はなくなります。
編集:。 ここで指定されているようにhttps://docs.mongodb.com/master/reference/connection-string/ポート番号を設定する必要はありません。
{useNewUrlParser:true}
を追加するだけで十分です。。
誤ったES8デモコードMongoDB incが提供もこの警告を作成します。
MongoDBは次のアドバイスを提供しますが、これは正しくありません。
新しいパーサーを使用するには、オプション{useNewUrlParser:true}をMongoClient.connectに渡します。
これを行うと、次のエラーが発生します。
TypeError:
executeOperation
への最後の引数はコールバックでなければなりません。
代わりにオプションは「新しいMongoClient」:に提供する必要があります。
以下のコードを参照してください。
const DATABASE_NAME = 'mydatabase'、。
URL = `mongodb:// localhost:27017 / $ {DATABASE_NAME}`。
module.exports = async function(){。
const client = new MongoClient(URL、{useNewUrlParser:true})。
var db = null。
{を試してください。
//これは壊れることに注意してください。
// client.connectを待ちます({useNewUrlParser:true})。
client.connect()を待ちます。
db = client.db(DATABASE_NAME)。
}キャッチ(エラー){。
console.log(err.stack)。
}。
dbを返します。
}。
``。
expressJS、api呼び出しケース、json送信の完全な例は次のとおりです。
...
app.get('/api/myApi', (req, res) => {
MongoClient.connect('mongodb://user:[email protected]:port/dbname',
{ useNewUrlParser: true }, (err, db) => {
if (err) throw err
const dbo = db.db('dbname')
dbo.collection('myCollection')
.find({}, { _id: 0 })
.sort({ _id: -1 })
.toArray(
(errFind, result) => {
if (errFind) throw errFind
const resultJson = JSON.stringify(result)
console.log('find:', resultJson)
res.send(resultJson)
db.close()
},
)
})
}
**We were using**
mongoose.connect("mongodb://localhost/mean-course").then(
(res) => {
console.log("Connected to Database Successfully.")
}
).catch(() => {
console.log("Conntection to database failed.");
});
*-----> This gives url parser error*
**Correct Syntax is**:
mongoose.connect("mongodb://localhost:27017/mean-course" , { useNewUrlParser: true }).then(
(res) => {
console.log("Connected to Database Successfully.")
}
).catch(() => {
console.log("Conntection to database failed.");
});
これが私のやり方です。数日前にnpmを更新するまで、ヒントがコンソールに表示されませんでした。
.connectには3つのパラメーター、URI、オプション、およびエラーがあります。
mongoose.connect(
keys.getDbConnectionString(),
{ useNewUrlParser: true },
err => {
if (err) throw err;
console.log(`Successfully connected to database.`);
}
);
以下のようにデータベースに接続する前に、次の設定を行うだけです。
const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect('mongodb://localhost/testaroo');
また、。
Replace update() with updateOne(), updateMany(), or replaceOne()
Replace remove() with deleteOne() or deleteMany().
Replace count() with countDocuments(), unless you want to count how many documents are in the whole collection (no filter).
In the latter case, use estimatedDocumentCount().
mongoデータベースとしてmlab.comを使用していました。 接続文字列をconfigという名前の別のフォルダーに分離し、keys.js内に接続文字列を保持しました。
<。!-スニペットを開始:js hide:false console:true babel:false -->。
module.exports = {
mongoURI: "mongodb://username:[email protected]:47267/projectname"
};
<。!-終了スニペット-->。
サーバーコードはそうでした。
<。!-スニペットを開始:js hide:false console:true babel:false -->。
const express = require("express");
const mongoose = require("mongoose");
const app = express();
//DB config
const db = require("./config/keys").mongoURI;
//connect to mongo DB
mongoose
.connect(
db,
{ useNewUrlParser: true } //need this for api support
)
.then(() => console.log("mongoDB connected"))
.catch(err => console.log(err));
app.get("/", (req, res) => res.send("hello!!"));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`)); //tilda not inverted comma
<。!-終了スニペット-->。
上記のように、接続文字列の後に{useNewUrlParser:true}と記述する必要があります。
単にあなたがする必要があると言います:
<。!-スニペットを開始:js hide:false console:true babel:false -->。
mongoose.connect(connectionString,{ useNewUrlParser: true }
//or
MongoClient.connect(connectionString,{ useNewUrlParser: true }
<。!-終了スニペット-->。
私のプロジェクトでは、マングースバージョン5.xを使用しています。 マングースパッケージを要求した後、値をグローバルに以下のように設定します。
const mongoose = require('mongoose');
// set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
mongoose.set('useNewUrlParser', true);
仲間を笑顔にしてください:)。
username
または password
に @
文字がある場合。 次に、このように使用します。
mongoose
.connect(
'DB_url',
{ user: '@dmin', pass: 'p@ssword', useNewUrlParser: true }
)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.log('Could not connect to MongoDB', err));