Search code examples
javascriptexpressnedb

How to add a key-value pair to a req.body dictionary during a POST request


I'm using NEDB and Express / Node.

This is my API:

app.post('/api/texts/', function (req, res, next) {

    (req.body).push({
      key:   "additionalField",
      value: 0
    });

    texts.insert(req.body, function (err, text) {
        if (err) return res.status(500).end(err);
        return res.json(text);
    });
});

I'm trying to add my own key to the body dictionary (I want the keys value to be an int).

The current ode gives me an error saying "TypeError: req.body.push is not a function".


Solution

  • Why dont you make a new object? For example:

    app.post('/api/texts/', function (req, res, next) {
        const obj = {};
        for (let [key, value] of Object.entries(req.body)) {
            obj[key] = value;
        }
        obj.additionalField = 0;
    
    
        texts.insert(obj, function (err, text) {
            if (err) return res.status(500).end(err);
            return res.json(text);
        });
    });
    

    Or you can simply use req.body.additionalField = 0; instead of creating a new object