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 }
私は答えを見つけました(ドキュメントは非常に不可解です。これが他の人に役立つことを願っています)
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)
})
})
Model.CompletedSentences.fetchAll().then(function (resData) {
console.log(resData.serialize())
})
出力はjson形式です
Collection
クラスには、このためのlodashメソッドのセットがあります。
このようにcollection.forEach
を使用できます。
new Model.CompletedSentences().fetchAll().then(function (completedSentences) {
completedSentences.forEach(function (model) {
console.log(model.attributes)
})
})
docs を確認してください。Collection
には他にも多くの便利なメソッドがあります。
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');
})
})
単にそれの属性でコンソールします。
console.log(resData.attributes);
オブジェクト万力の結果が得られます。