Search code examples
javascriptangularjsjsoncouchdbseamonkey

JSON in CouchDB stange behavior


I've created updates handler in CouchDB with test code like this(before inserting in Couch I'm removing newlines):

function (doc, req) {
    if (req['userCtx']['roles'].indexOf('editor') < 0) {
        return [null, 'Access denied'];
    }
    if (!doc) {
        if (/*!('_id' in req) &&*/ !req['_id'] /*&& 'title' in req['body']*/ && !!req['body']['title'] /*&& 'content' in req['body']*/ && !!req['body']['content']) {
            return [{ 'title': req['body']['title'], 'content': req['body']['content'], 'date': new Date(), 'edited_by': req['userCtx']['name'] }, 'Created' + toJSON(req)];
        }
        return [null, 'Empty' + toJSON({ 'no_id': !req['_id'], 'title': !!req['body']['title'], 'content': !!req.body['\"content\"'], 'body':req.body })];
    }
    doc['date'] = new Date();
    doc['edited_by'] = req['userCtx']['name'];
    return [doc, 'Edited' + toJSON(doc)];
}

Angular sends data in POST call

{"title":"test","content":"test"}

In return I'm getting

Empty{"no_id":true,"title":false,"content":false,"body":"{\"title\":\"test\",\"content\":\"test\"}"}

What's wrong? Why it don't want to see received object not in direct a.b, not in hash a['b'], not in even escaped a['\"b\"']? I'm hoping that's my fault, not couch's. How to do it right?


Solution

  • You have to parse the body to JSON first...

    Use body-parser as described here: https://scotch.io/bar-talk/expressjs-4-0-new-features-and-upgrading-from-3-0