我正在尝试获取数据库中的项目计数以确认数据插入是否成功。
- 插入前获取计数
- 插入
- 插入后获取计数
- 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));
};
获取DB计数函数
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
};
我收到错误,因为返回是在所需操作完成之前发生的。
感谢您的帮助。
<小时/>[编辑]带有 Promise 的 getCount 函数
我已将 Promise 添加到 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()}之前执行。在数据库操作完成之前,它返回未定义。
最佳答案
一般来说,您遇到的问题是您希望函数返回时该值已经存在。对于异步函数来说,情况通常并非如此。有大量关于异步处理的信息(不要与 Java 中的并行处理相混淆)。
我创建了一个适合您情况的示例:
https://jsfiddle.net/rh3gx76x/1/
var dummyCount = 5
getCount = function() {
return new Promise(function(resolve, reject) {
setTimeout(function() { // this would be your db call, counting your documents
resolve(dummyCount); // dummy for number of documents found
}, 100 * Math.random());
});
};
insertMany = function() {
return new Promise(function(resolve, reject) {
setTimeout(function() { // this would be your db call, writing your documents
dummyCount += 2;
resolve();
}, 100 * Math.random());
});
};
runIt = function(callback) {
var count1;
getCount().then(function(count) {
console.log("First callback with value ", count);
count1 = count;
insertMany().then(function() {
getCount().then(function(count2){
console.log("Second callback with value ", count2);
callback(null, count1, count2);
});
})
})
}
runIt(function(err, count1, count2) {
console.log("count1: " + count1 + ", count2: " + count2);
});
最后一件事。您可能想查看“async”包。这对解决这些问题有很大帮助,提供了很多帮助函数和控制流内容。
关于javascript - Node.js | MongoDB 计数() : Getting Count Before and After Inserting Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41781807/