A.D*_*A.D 18 javascript bookshelf.js knex.js
我有一个MySQL数据库,我需要从node.js查询
我正在使用书架和knex.
我想获取表的内容 - 我已经在我的model.js文件中定义了一个表.我正在尝试这样的查询:
//select * from completedSentences;
Model.CompletedSentences.fetchAll().then(function (resData) {
console.log(resData)
})
Run Code Online (Sandbox Code Playgroud)
我想知道如何循环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 }
Run Code Online (Sandbox Code Playgroud)
A.D*_*A.D 21
我找到了答案(文档很神秘,希望这有助于其他人)
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)
})
})
Run Code Online (Sandbox Code Playgroud)
小智 11
Model.CompletedSentences.fetchAll().then(function (resData) {
console.log(resData.serialize())
})
Run Code Online (Sandbox Code Playgroud)
输出是json格式
http://bookshelfjs.org/#Model-instance-serialize
该Collection班有一组lodash方法这一点.
你可以这样使用collection.forEach:
new Model.CompletedSentences().fetchAll().then(function (completedSentences) {
completedSentences.forEach(function (model) {
console.log(model.attributes)
})
})
Run Code Online (Sandbox Code Playgroud)
查看文档,还有许多其他有用的方法Collection.