【问题标题】:for loop giving an error while inserting document to collection将文档插入集合时for循环出错
【发布时间】:2016-08-23 21:31:09
【问题描述】:

在 node.js 中,我正在编写将文档插入集合的查询,但该查询仅插入一个文档。下面是js代码,

app.js

router.post('/creatList', function(req,res){
    console.log(req.body.email);
    var emails = req.body.email;

    if(req.body.wData.wishListType == 'Shared'){
        var findUsers = function(db, callback) {


            var cursor;
            cursor = db.collection('users').find({email: { $in: emails }})

            cursor.toArray(function(err, docs){
                if(err){
                    callback(new Error("Some problem"));
                } else {
                    callback(null,docs);
                } 
            });     
        };

        MongoClient.connect(config.database, function(err, db) {
            assert.equal(null, err);
            findUsers(db, function(err,docs) {
                db.close();
                console.log(docs);
                var inserts_processing = 0;
                for(var key in docs){
                    console.log(key);
                    var ids = docs[key]._id;
                    inserts_processing++;
                    console.log(ids);

                    var insertDocument = function(db, callback) {
                        db.collection('notifications').insertOne({
                            "userId" : ids,
                        },function(err, result) {
                             inserts_processing--;
                            assert.equal(err, null);
                            console.log("Inserted a document into the notifications collection.");
                             if(inserts_processing == 0){
                                db.close();
                                callback();
                            }
                        });
                    };

                    MongoClient.connect(config.database, function(err, db) {
                        assert.equal(null, err);
                        insertDocument(db, function() {
                            db.close();
                        });
                    });
                }
            });
        });     


        } else {
            console.log("other");
        }

    });

在上面的代码中,console.log 包含两个 ids 570dec75cf30bf4c09679deb 56fe44836ce2226431f5388f 但实际上它只插入了最后一个。

【问题讨论】:

  • 您的路线没有任何响应?而且我不明白为什么您每次需要时都打开/关闭 MongoDB 连接。
  • 没有路线工作正常

标签: node.js mongodb


【解决方案1】:

根据您更新的代码,我将尝试以下操作

router.post('/creatList', function(req,res){
    console.log(req.body.email);
    var emails = req.body.email;

    if(req.body.wData.wishListType == 'Shared'){

        // Open one connection to find users and insert documents
        MongoClient.connect(config.database, function(err, db) {
            assert.equal(null, err);

            if(!err){
                findUsers(db, function(err,docs) {

                    if(!err){
                        insertDocs(db, docs, function(){
                            db.close(); // Close connection

                            console.log("All documents have been inserted");
                            res.status(200).send("All is OK");
                        });
                    }

                });
            });     
        }   

    } else
        console.log("other");

});


function insertDocs(db, docs, callback){
    var inserts_processing = 0; // Will contain the number of inserts pending operation     
    for(var key in docs){
        var ids = docs[key]._id;
        inserts_processing++; // Before writing data, add one to processing inserts

        db.collection('notifications').insertOne({
            "userId" : ids,
        }, function(err, result) {
            inserts_processing--; // One insert have been finished, so remove one

            assert.equal(err, null);
            console.log("Document inserted into the notifications collection.");

            // If all inserts have been finished, call back the function
            if(inserts_processing == 0)
                callback();

        });
    }
} 


function findUsers(db, callback) {
    var cursor;
    cursor = db.collection('users').find({email: { $in: emails }})

    cursor.toArray(function(err, docs){
        if(err)
            callback(new Error("Some problem"));
        else 
            callback(null,docs);
    });     
};

【讨论】:

  • 它不工作。我已经编辑了我的问题,请看。
猜你喜欢
  • 2018-02-07
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
相关资源
最近更新 更多