Search code examples
node.jsmongodbmongoskin

Inserting a JSON variable


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.


Solution

  • 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){
      //...
    })