weixin_33716941 2013-10-28 17:48 采纳率: 0%
浏览 344

Node.js mongodb批量插入

i'm kinda new to node.js and mongo and i'm having a little problem. I can't bulk insert documents into mongodb using ajax on client and nodejs/express on server. Here is my client code:

<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 
            });
        });

And here is my route handler in node:

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
        }
    })
 });

})

I'm getting data nicely with console.log(docs), but my test collection is empty. What am i missing? Thanks

  • 写回答

1条回答 默认 最新

  • 叼花硬汉 2016-10-13 09:24
    关注
     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');
                });
     })
    

    you need to define test schema and test model correctly. For further details you can read following links https://docs.mongodb.com/manual/reference/method/Bulk.insert/

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!