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
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/