Mongodb.connect不执行回调函数

时间:2018-08-17 07:51:54

标签: node.js mongodb

我正在尝试连接到我的Mongodb并插入一些文档(如果它们尚未在数据库中)。

第一次插入时效果很好,但是在函数existInDatabase中,有时它不执行回调函数。

Date.toTimeString()

2 个答案:

答案 0 :(得分:0)

db.db(dbName).collection(collection).find({}) returnscursor每个文档。您缺少.toArray()

db.db(dbName).collection(collection).find({}).toArray()...

答案 1 :(得分:0)

我对您的代码进行了一些更改。看来您是异步编程的新手,请花一些时间来了解流程。随时进行任何进一步的查询。这是您的代码。

// Welcome to aync programming
// Here no one waits for the slow processes


 var MongoClient = require('mongodb').MongoClient;
 var mongoData = require('./mongoData');
 var exports = module.exports = {};
 var dbName = 'checklist';


 // Make the connection for once only 
 MongoClient.connect(mongoData.ConString, { useNewUrlParser: true },       
 function(err, db) {
  if (err) throw err;
 var myDB = db.db(dbName); // create DB for once 

 for (var key in mongoData.Customers) {

     //make call to the function and wait for the response
     existsInDatabase(mongoData.Customers[key], 'Customers', function(err, result) {
         //once the response came excute the next step
         if (result) {
             myDB.collection('Customers').insertOne(mongoData.Customers[key], function(err, res) {
                 if (err) throw err;
                 console.log('1 document inserted');
             });
         }
     });
 }
 for (var key in mongoData.Categorys) {
     //make call to the function and wait for the response
     existsInDatabase(mongoData.Customers[key], 'Customers', function(err, result) {
         //once the response came excute the next step
         if (result) {
             myDB.collection('Categorys').insertOne(mongoData.Categorys[key], function(err, res) {
                 if (err) throw err;
                 console.log('1 document inserted');
             });
         }
     });
 }

 // Both the for loop will work randomly without any order


 function existsInDatabase(obj, collection, cb) {
     var result = false;
     myDB.collection(collection).findOne({ id: obj.id }, function(err, result)     
 {
         if (err) {
             //this cb will work only when db operation is complited
             cb(err);
         } else if (result) {
             cb(null, true);
         } else {
             cb(null, false);
         }
     });
 }
});

此代码可能会导致某些错误。随时提出更多问题

相关问题