如何在 .fetchAll Bookshelf js + knex js 之后循环遍历行?

How to loop over rows after .fetchAll Bookshelf js + knex js?

我有一个 MySQL 数据库,我需要从 node.js

查询

我正在为此使用书架和 knex。

我想获取 table 的内容 - 我在 model.js 文件中定义了 table。我正在尝试这样的查询:

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

我找到了答案(文档很隐晦,希望这对其他人有帮助)

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

    })

Collection class 有一套 lodash 方法。

您可以这样使用collection.forEach

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

查看docsCollection还有许多其他有用的方法。

如果你不想使用 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');
    })

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

输出为 json 格式

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

简单地安慰一下它的属性。

console.log(resData.attributes);

你会得到对象虎钳的结果。

答案很简单,试试这个 console.log(resData.toJSON())