I'm trying to insert a json, which originates from a POST request, as a document into a mongodb collection. I'm using node.js and Express 4.
My code:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const request = require('request');
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
app.use(bodyParser.urlencoded({ extended: false, limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
var insertReading = function(datum, db) {
var collection = db.collection('readings');
collection.insertOne(JSON.parse(datum), function(err, r) {
assert.equal(err, null);
assert.equal(1, r.insertedCount);
});
}
app.post('/save/', function (req, res) {
console.log(req.query);
console.log(req.body);
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertReading(req.body), db);
db.close();
});
res.send('All done!');
});
When looking at the created document, it looks like that:
> for (var key in db.readings.findOne()) {print(key, typeof key);}
_id string
payload string
I'd expect the payload to be a whole document, with more keys in it etc. but it is just a string.
I can later convert this payload into a document:
db.readings.find().forEach(function(myDoc) {db.parsed.insertOne(JSON.parse(myDoc['payload']));});
but I would like to just get it right on the first insertion...
I already tried adding JSON.parse to the node.js code, but it does not help, though on the shell command it does the trick...
What am I doing wrong? Is there a function I can't find that turns a json string into a document upon insertion?
via scf
No comments:
Post a Comment