2015-11-24 11 views
13

私はnode.jsからクエリする必要があるMySQLデータベースを持っています.fetchAllの後に行をループする方法Bookshelf js + knex js?

私は本棚とknexを使っています。

テーブルの内容を取得したい - 私のmodel.jsファイルにテーブルを定義しました。それは複数の行でなければなりませんので、私はどのようにresDataをループに知っていただきたいと思います

//select * from completedSentences; 
Model.CompletedSentences.fetchAll().then(function (resData) { 
     console.log(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 } 

答えて

19

私の答え(ドキュメントは非常に不可解で、これは他の人に役立ちます願っています)

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) 
     }) 

    }) 
+0

うわー、私はすべてのドキュメント上で見て、できなかったですこの単純なことをする方法を見つける – Jonah

+0

私はそれを探して正確に私の考え... –

+0

私のために私はresult.lenghtが等しいことがわかったresult.models.length ((( –

3

Collectionクラスは、このためのlodashメソッドのセットを持っていました。

あなたはcollection.forEachをこのように使用することができます。

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

チェックアウトdocsCollectionのための多くの他の有用な方法があります。

1

あなたが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'); 
    }) 

}) 
4
Model.CompletedSentences.fetchAll().then(function (resData) { 
     console.log(resData.serialize()) 
    }) 

出力がJSON形式で

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

+1

これは受け入れられる回答でなければなりません。シンプルでダイレクト。 –

+0

あなたは本当のMVP @RalleSaidです –

関連する問題