1

My code is below:

req.on('data', function(chunk) {
    console.log(JSON.stringify(chunk.toString('utf8')));
    db.collection('collectionname').insert(chunk.toString('utf8'), function(err, result) {
         if (err) throw err;
         if (result) console.log("Added!");
    });
 });

The console.log prints the right message with JSON format, but this code can't insert the chunk in MongoDB.

So my question is how to insert JSON variable in MongoDB. Thanks in advance.

Rich Churcher
  • 7,361
  • 3
  • 37
  • 60
Courage
  • 543
  • 5
  • 25
  • 1
    Why can't it? Any error messages? – E_net4 Oct 14 '15 at 09:42
  • Also, I would advise you to see this answer, as you seem to be making the same mistake. Data is received in chunks that might only make sense when merged. http://stackoverflow.com/a/26807694/1233251 – E_net4 Oct 14 '15 at 09:45

1 Answers1

1

insert method of Mongo collection accepts either document or an array of documents, and you passing a string to it.

db.collection('collectionname').insert({
  chunk: chunk.toString('utf8')
}, function(err, result){
  //...
})
Juicy Scripter
  • 25,778
  • 6
  • 72
  • 93