如何使用REST和节点将项插入到数组中

时间:2016-10-27 10:37:10

标签: javascript arrays node.js rest

我正在使用节点使用REST API将项目存储在Firebase数据库中。我不明白的是如何在数组中追加一个项目。因此,例如,要将新项目附加到数据库,我正在使用PATCH:

const https = require('https');
var patchData = '{"thing":"value"}';

var options = {
    host: 'mydatabase.firebaseio.com',
    path: '/items.json',
    method: 'PATCH',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(patchData)
    }
};

var req = https.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Body: ' + chunk);
    });
    res.on('end', function() {
        //do end clean up
    });
});

req.on("error", function(e) {
    console.log('problem with request: ', e.message);
});

//write data to request body
req.write(patchData);
req.end();

我可以追加或替换对象没问题,并获得这样的结构:

{
    "items": {
        "thing1": "value1",
        "thing2": "value2",
        "thing3": "value3"
    }
}

我想要的结构是:

{
    "items": [{"thing1": "value1"},
        {"thing2": "value2"},
        {"thing3": "value3"}]
}

由于每个项目大致是同一类物品的集合,而不是物品对象的属性。

要么我缺少一些简单的东西,要么需要首先读取整个数组,然后将其附加到节点中,并一次性重写回Firebase,但这看起来非常低效。我如何获得第二个结构?

0 个答案:

没有答案