web-dev-qa-db-ja.com

.fetchAll Bookshelf js + knex jsの後に行をループする方法は?

Node.jsからクエリを実行する必要があるMySQLデータベースがあります

これには本棚とknexを使っています。

テーブルの内容を取得したいのですが、model.jsファイルにテーブルを定義しました。私はこのようなクエリを試みています:

//select * from completedSentences;
Model.CompletedSentences.fetchAll().then(function (resData) {
        console.log(resData)
    })

複数行になるはずなので、resDataをループする方法を教えてください。

コンソールの出力は次のようになります。ループできる行のリストが表示されません。何が欠けていますか?

CollectionBase {
  model:
   { [Function]
     NotFoundError: [Function: ErrorCtor],
     NoRowsUpdatedError: [Function: ErrorCtor],
     NoRowsDeletedError: [Function: ErrorCtor] },
  length: 1,
  models:
   [ ModelBase {
       attributes: [Object],
       _previousAttributes: [Object],
       changed: {},
       relations: {},
       cid: 'c4',
       id: 1 } ],
  _byId:
   { '1':
      ModelBase {
        attributes: [Object],
        _previousAttributes: [Object],
        changed: {},
        relations: {},
        cid: 'c4',
        id: 1 },
     c4:
      ModelBase {
        attributes: [Object],
        _previousAttributes: [Object],
        changed: {},
        relations: {},
        cid: 'c4',
        id: 1 } },
  _knex: null,
  _events: {},
  _eventsCount: 0 }
18
A.D

私は答えを見つけました(ドキュメントは非常に不可解です。これが他の人に役立つことを願っています)

new Model.CompletedSentences().fetchAll().then(function (resData) {
        _.each(resData.models, function (model) { //I am looping over models using underscore, you can use any loop
            console.log(model.attributes)
        })

    })
21
A.D
Model.CompletedSentences.fetchAll().then(function (resData) {
        console.log(resData.serialize())
    })

出力はjson形式です

http://bookshelfjs.org/#Model-instance-serialize

12
RalleSaid

Collectionクラスには、このためのlodashメソッドのセットがあります。

このようにcollection.forEachを使用できます。

new Model.CompletedSentences().fetchAll().then(function (completedSentences) {
        completedSentences.forEach(function (model) {
            console.log(model.attributes)
        })    
    })

docs を確認してください。Collectionには他にも多くの便利なメソッドがあります。

6
pietrovismara

Lodashを使用したくない場合は、これを行うことができます。

new Model.CompletedSentences().fetchAll().then(function (resData) {
    resData.models.forEach( function (model) { 
        console.log(model.get('attribute');
        console.log(model.related('sth').get('attribute');
    })

})
3
Salar

単にそれの属性でコンソールします。

console.log(resData.attributes);

オブジェクト万力の結果が得られます。

0
Chaudhary