データの挿入が成功したことを確認するために、データベース内のアイテムの数を取得しようとしています。私は、これはいくつかの簡単な関数を使用して実装することができます知っている:Node.js | MongoDB count():データの挿入前後のカウントの取得
- は
- 挿入
- 要約
注CONSOLE.LOG
dbName.equal(insertSize, result.insertedCount)
ただし、私はjavascriptを初めて使用しています私は非同期コールバックを実装する必要があると思っているので、これを理解したいと思いました。
挿入機能
var insertMany = function() {
// get initial count
var count1 = getDbCount();
// Insert new 'data'
MongoClient.connect(url, function(err, db) {
var col = db.collection(collectionName);
col.insert(data, {w:1}, function(err,result) {});
db.close();
});
/** This needs to be implemented through next/callback
after the insert operation **/
var count2 = getDbCount();
/** These final console logs should be executed after all
other operations are completed **/
console.log('[Count] Start: ' + count1 + ' | End:' +count2);
console.log('[Insert] Expected: ' + data.length + ' | Actual: ' + (count2 - count1));
};
は、必要な操作が完了する前にリターンが発生しているので、私はエラーを取得しています
var getDbCount = function() {
MongoClient.connect(url, function(err, db) {
if (err) console.log(err);
var col = db.collection(collectionName);
col.count({}, function(err, count) {
if (err) console.log(err);
db.close();
console.log('docs count: ' + count);
// This log works fine
});
});
return count; // this is returning as undefined since this is
// executing before the count operation is completed
};
DBカウント機能を取得します。
ありがとうございました。
[EDIT]同様にgetCount機能約束
と私は開始と同様にgetCount機能への約束を追加しました:
var getCount = function() {
var dbCount = 0;
var promise = new Promise(function(resolve, reject) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log('Unable to connect to server', err);
} else {
console.log('Database connection established:' + dbName);
}
// Get the collection
var col = db.collection(collectionName);
col.count({}, function(err, count) {
if (err) console.log(err);
db.close();
console.log('docs count: ' + count);
resolve(null);
dbCount = count;
});
});
});
promise.then(function() {
return dbCount;
});
};
console.log(getCount());
は、出力はまだです: 未定義 データベース接続確立された:testdb ドキュメント数:500
それから、({return count})コードはpromise {db.count()}の前に実行されています。データベース操作が完了する前にundefinedを返します。
あなたが試したことを表示しないと間違ったことを伝えるのはちょっと難しいことです。エラーには、エラーが発生した行に関する情報が必要です。エラーが発生したコードブロックと少なくとも呼び出された部分を提供してください – newBee
こんにちはnewBee、私はそれを取り上げました。私はコールバックを使って実装することに多くの進歩を遂げていませんでした。なぜならそれが含まれていなかったからです。進歩したら、新しいコードを更新して追加します。ありがとう – carlolm
@ CarloP.LasMarias決して 'setTimeout'に決めるべきではありません。特にバックエンドには機能の残虐行為を説明する記事がたくさんあります。プロミスはそのような条件を処理するために開発されたモジュールであり、それがうまくいかない場合、問題はどこかにあるコード内にあります。 Async.jsは 'setTimeout'よりはるかに優れたオプションです。 –