web-dev-qa-db-ja.com

knex.js /bookshelf.jsでカウント結果を取得する

Knexを使用して単純なカウントを実行しようとしています( 本棚ではまだサポートされていないようです )。次のコードが機能しています。

_bookshelf.knex('hosts').count('id').then(function(total) {
  res.send({
    meta: {
      total: total[0]['count(`id`)']
    }
  });
});
_

実際の結果を得るためにtotal[0]['count('id')']を実行しなければならないのは奇妙に思えます。私はここで何かをしていますか?

ありがとう!

14
Pedro

Knex.jsからの結果はすべて配列です。クエリは成功し、単に0の結果を返す可能性があります。

また、列名で直接列のエイリアスを作成することもできます(またはcount()呼び出し)。このような:

  bookshelf.knex('hosts').count('id as CNT').then(function(total) {
    res.send({
      meta: {
        total: total[0].CNT
      }
    });
  });

それでも最初の要素を取得する必要がありますが、通常のJSONプロパティとして列を参照できます。

18
clay

これは正しく機能しているようで、少し簡単です

knex('Quotes').count('quoteBody')
    .then((res)=>{
        //console.log("rows "+JSON.stringify(res))        
        console.log("rowspl2 "+res[0]['count(`quoteBody`)'])
    })
    .catch((err)=>{
        console.log("err "+err)
    })

またはこのように試してください

    knex('Quotes').count('quoteBody', {as: 'rows'})
        .then((res)=>{
           // console.log("rows "+JSON.stringify(res))
            console.log("rowsp "+res[0]['rows'])
        })
        .catch((err)=>{
            console.log("err "+err)
        })
0
UserCah

Knexは結果を配列として返しますが、最初の結果を返すメソッドもあります。これは、配列ではなくオブジェクトになります。配列内のカウントにアクセスするために[0]などに依存することなく、カウントに直接到達するのは非常に簡単です。あなたの例では、よりクリーンなソリューションは次のようになります。

bookshelf
  .knex("hosts")
  .count("id")
  .first()
  .then(function(total) {
    res.send({
      meta: {
        total: total.count
      }
    });
  });
0
Ryan Brockhoff