【发布时间】:2017-01-21 16:37:02
【问题描述】:
我正在尝试获取数据库中的项目计数以确认数据插入成功。
- 插入前获取计数
- 插入
- 插入后获取计数
- 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
};
我收到错误,因为在所需操作完成之前发生退货。
感谢您的帮助。
[EDIT] 带有 Promise 的 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
then({return count}) 代码仍然在 promise {db.count()} 之前执行。在数据库操作完成之前返回 undefined。
【问题讨论】:
-
如果你不展示你尝试过的东西,就很难说出你做错了什么。该错误应该带有一些关于错误发生在哪一行的信息。提供发生错误的代码块以及至少调用它的部分
-
嗨 newBee,我已经把它拿出来了。我在通过回调实现方面没有取得太大进展,这就是我没有包含它的原因。如果我取得进展,我将更新并添加新代码。谢谢
-
@CarloP.LasMarias 你永远不应该选择
setTimeout。有很多文章专门在后端解释了该功能的暴行。 Promise 是为处理此类情况而开发的模块,如果它不起作用,则问题出在代码中,需要解决。 Async.js 是另一个比setTimeout更好的选择。
标签: javascript node.js mongodb