Courage
Courage

Reputation: 543

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.

Upvotes: 1

Views: 68

Answers (1)

Juicy Scripter
Juicy Scripter

Reputation: 25938

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

Upvotes: 1

Related Questions