1

Express + NodeJS アプリでエラーが発生しています。CoinAPI.io の API を使用していますが、過去に API からの応答としてバイト配列を取得する際に問題がありました。私はこの問題を調査し、過去に で解決したBuffer.concatので、フロントエンドに json オブジェクトを応答として送信できます。以下のコード:

app.get('/build', function(req, res){
    console.log('Building the database...');

    // make client connect to mongo service
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        console.log("SUCCESS: Database created");
        let dbo = db.db('lab5');

        // Craft request header
        const options = {
            "method": "GET",
            "hostname": "rest.coinapi.io",
            "path": "/v1/assets",
            "headers": {'X-CoinAPI-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'}
        };

        // Send request to CoinAPI.io
        const request = https.request(options, response => {
            let chunks = [];
            response.on("data", chunk => {
                chunks.push(chunk);
            });
            response.on('end', () => {
                let json = Buffer.concat(chunks);

                // Insert into the database
                dbo.collection('crypto').insertMany(json, function(insertErr, insertRes) {
                    if (insertErr) throw insertErr;
                    console.log("Number of documents inserted: " + insertRes.insertedCount);
                    db.close();
                });
                console.log('End of request stream')
            });
        });

        request.end();

        // print database name
        console.log("NOTE: db object points to the database : "+ db.databaseName);
        db.close();
    });
    res.end();
})

これは以前は機能していましたが、取得したデータを MongoDB データベースに挿入する必要があります。insertManyそこで、 から作成しているbodyオブジェクトに対してを実行しようとしましたBuffer.concat。しかし、今では次のエラーが発生します。

MongoError: docs parameter must be an array of documents

console.log(json)コレクションの挿入の前に実行しました。本体は、連結を行ったばかりのバイト配列をコンソールにダンプしますが、その理由はわかりません。

編集: の使用に関する Sohail への応答として.toJSON()、これは、バッファーを json に変換しようとしたときに発生したことです。

let buf = Buffer.concat(chunks);
let json = buf.toJSON();
console.log(json);

そして、ログjsonをコンソールすると...

{
  type: 'Buffer',
  data: [
     91,  10,  32,  32, 123,  10,  32,  32,  32,  32,  34,  97,
    115, 115, 101, 116,  95, 105, 100,  34,  58,  32,  34,  78,
     80,  88,  83,  34,  44,  10,  32,  32,  32,  32,  34, 110,
     97, 109, 101,  34,  58,  32,  34,  80, 117, 110, 100, 105,
     32,  88,  34,  44,  10,  32,  32,  32,  32,  34, 116, 121,
    112, 101,  95, 105, 115,  95,  99, 114, 121, 112, 116, 111,
     34,  58,  32,  49,  44,  10,  32,  32,  32,  32,  34, 100,
     97, 116,  97,  95, 115, 116,  97, 114, 116,  34,  58,  32,
     34,  50,  48,  49,
    ... 5165802 more items
  ]
}

それでもバイト配列/バッファを挿入するというエラーが発生します

4

1 に答える 1

1

Bufferオブジェクトをオブジェクトに変換する必要がありmongo documentます。method を使用してから、 methodbuffer.toString()で解析してJSON.parseに変換stringできobjectます。

これを試して。

let buf = Buffer.concat(chunks);
let json = JSON.parse(buf.toString());
// Insert into the database
dbo.collection('crypto').insertMany(json, function (insertErr, insertRes) {
    if (insertErr) throw insertErr;
    console.log("Number of documents inserted: " + insertRes.insertedCount);
    db.close();
});
console.log('End of request stream');
于 2020-04-11T03:12:54.190 に答える