首页 文章

Node.js mongodb批量插入

提问于
浏览
0

我是node.js和mongo的新手,我有一点问题 . 我无法使用客户端上的ajax和服务器上的nodejs / express将文档批量插入mongodb . 这是我的客户端代码:

<button class="btn>Send</button>
data = {'test':'test1','test':'2','test':'test1','test':'test2','test':'test1','test':'test2'}

        $(".btn").click(function(){
            $.ajax({
                url: 'http://localhost:8000/2',
                type: 'post',
                dataType: 'json',
                data: data 
            });
        });

这是节点中的路由处理程序:

app.post('/2', function(req, res){
var docs = [];
 for(var i = 0; i < 10000; i++) {
     docs[i] = req.body;
 }

 db.collection('test', function(err, collection){
    collection.insert(docs, function(err, result) {
        if (!err) {
            console.log(result);
            res.end();
        } else {
            throw err
        }
    })
 });

})

我正在使用console.log(docs)很好地获取数据,但我的测试集合是空的 . 我错过了什么?谢谢

1 回答

  • 0
    app.post('/2', function(req, res){
      var docs = req.body.data; // ur json data is now in node end        
      var i=0;
      var bulk = test.collection.initializeUnorderedBulkOp();  // test is the        model name. I used mongoose  
      // now using loop insert all json data inside bulk variable   
      for (i = 0; i < docs.length; i += 1) {
         bulk.insert(docs[i]);
      }
    
      //after insertion finished u might need node-async module, to insert first 
      //then asynchronously execute bulk 
       bulk.execute(function (errx) {
             if (errx) { return next(errx); }
                         console.log('Success');
                });
     })
    

    您需要正确定义测试模式和测试模型 . 有关详细信息,请阅读以下链接https://docs.mongodb.com/manual/reference/method/Bulk.insert/

相关问题