GithubHelp home page GithubHelp logo

loopback-example-database's Introduction

loopback-example-database

⚠️ This LoopBack 3 example project is no longer maintained. Please refer to LoopBack 4 Examples instead. ⚠️

A tutorial for basic database related features.

Overview

Topics covered

  • Data sources
    • Creating
    • Configuring
  • Models
    • Creating
  • Automigration
  • Instance introspection (Discovery)

Database specific tutorials

Database specific tutorials are on separate branches. The master branch contains the tutorial for MongoDB.

Branch Connector
master MongoDB
mssql Microsoft SQL Server
mysql MySQL
oracle Oracle
postgresql PostgreSQL

For example, to view the MySQL example:

git clone https://github.com/strongloop/loopback-example-database
cd loopback-example-database
git checkout mysql

Prerequisites

Before starting this tutorial, make sure you have the following installed:

Running the example

git clone https://github.com/strongloop/loopback-example-database
cd loopback-example-database
npm install
npm start

Tutorial - MongoDB

1. Create a new LoopBack app

App info

  • Name: loopback-example-database
  • Dir to contain the project: loopback-example-database
lb app loopback-example-database

     _-----_
    |       |    ╭──────────────────────────╮
    |--(o)--|    │  Let's create a LoopBack │
   `---------´   │       application!       │
    ( _´U`_ )    ╰──────────────────────────╯
    /___A___\   /
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

? What's the name of your application? loopback-example-database
? Enter name of the directory to contain the project: loopback-example-database
     info change the working directory to loopback-example-database

? Which version of LoopBack would you like to use? 3.x (current)
? What kind of application do you have in mind? empty-server (An empty LoopBack API, without any c
onfigured models or datasources)

2. Install the LoopBack MongoDB connector

cd loopback-example-database
npm install --save loopback-connector-mongodb

3. Create a data source

Data source info

  • Data source name: accountDS
  • Select the connector for accountDS: MongoDB
lb datasource accountDS
... # follow the prompts

This creates a new data source named accountDS that uses the MongoDB connector.

4. Configure the data source

For the purposes of this example, we will use a preconfigured StrongLoop MongoDB server. Edit server/datasources.json to set the MongoDB configs:

{
  ...
  "accountDS": {
    "name": "accountDS",
    "connector": "mongodb",
    "host": "demo.strongloop.com",
    "port": 27017,
    "database": "demo",
    "username": "demo",
    "password": "L00pBack"
  }
}

Feel free to use your own local MongoDB instance. Simply change the configs above to match your own.

5. Create a new model

lb model
... # follow the prompts

Model Info

  • Model name: Account
  • Attach Account to: accountDS (mongodb)
  • Base class: PersistedModel
  • Expose via REST: Yes
  • Custom plural form: Leave blank
  • Properties:
    • email
      • String
      • Not required
    • createdAt
      • Date
      • Not required
    • lastModifiedAt
      • Date
      • Not required
slc loopback:model Account
... # follow the prompts

6. Create the collection with sample data - Automigration

With the account model configured, we can generate the corresponding MongoDB collection using the info from the Account metadata in common/models/account.json via auto-migration.

Start by creating a dir to store general-purpose scripts:

mkdir bin

Inside that dir, create a script named automigrate.js. To create the Account collection and create two sample accounts, run:

node bin/automigrate.js

WARNING

The automigrate function creates a new collection if it doesn't exist. If the collection already exists, it will be destroyed and it's data will be deleted. If you want to keep this data, use autoupdate instead.

You should see:

Created: { email: '[email protected]',
  createdAt: Thu Oct 22 2015 17:58:09 GMT-0700 (PDT),
  lastModifiedAt: Thu Oct 22 2015 17:58:09 GMT-0700 (PDT),
  id: 562986213ea33440575c6588 }
Created: { email: '[email protected]',
  createdAt: Thu Oct 22 2015 17:58:09 GMT-0700 (PDT),
  lastModifiedAt: Thu Oct 22 2015 17:58:09 GMT-0700 (PDT),
  id: 562986213ea33440575c6587 }

If you are using Node 4, it is safe to ignore Swagger: skipping unknown type "ObjectId". This warning will be addressed in a future update.

7. View data using the explorer

Projects scaffolded via slc loopback come with loopback-component-explorer preconfigured. From the project root, start the server:

node .

Then to view the existing account data, browse to localhost:3000/explorer and click:

  • GET /Accounts
  • Try it out!

You should see:

[
  {
    "email": "[email protected]",
    "createdAt": "2015-10-23T00:58:09.280Z",
    "lastModifiedAt": "2015-10-23T00:58:09.280Z",
    "id": "562986213ea33440575c6587"
  },
  {
    "email": "[email protected]",
    "createdAt": "2015-10-23T00:58:09.280Z",
    "lastModifiedAt": "2015-10-23T00:58:09.280Z",
    "id": "562986213ea33440575c6588"
  }
]

Try out some of the other endpoints to get a feel for how explorer works.

8. Add a script to perform instance instrospection (Discovery)

Discovery is the process of reverse engineering a LoopBack model from an existing database schema.

The LoopBack MongoDB connector does not support discovery. However, you can use instance instrospection, which creates a LoopBack model from an existing JavaScript object.

To do this, create a script named instance-introspections.js in the bin dir. Then run:

node bin/instance-introspection

You should see:

Created: { email: '[email protected]',
  createdAt: Thu Oct 22 2015 19:38:20 GMT-0700 (PDT),
  lastModifiedAt: Thu Oct 22 2015 19:38:20 GMT-0700 (PDT),
  id: 56299d9d71c7f600719ca39f }

See the official docs for more info.


More LoopBack examples

loopback-example-database's People

Contributors

0candy avatar agnes512 avatar amir-61 avatar bajtos avatar crandmck avatar dhmlau avatar jannyhou avatar mschmulen avatar raymondfeng avatar rmg avatar sam-github avatar siddhipai avatar smartmouse avatar superkhau avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loopback-example-database's Issues

MSSQL connection

Does the MSSQL example truly work, or is it theoretical? (can one actually connect to mssql.strongloop.com:1433 ?)

I got the following error when trying the discovery app:

[~/Desktop/Temp/loopback-example-database/server on mssql]$ DEBUG=loopback:datasource node discover.js
  loopback:datasource Settings: {"name":"db","debug":true} +0ms
  loopback:datasource Settings: {"name":"accountDB","connector":"mssql","host":"mssql.strongloop.com","port":1433,"database":"demo","username":"demo","password":"L00pBack","debug":true} +2ms
Connection fails:  { name: 'ConnectionError',
  message: 'Failed to connect to mssql.strongloop.com:1433 - connect ECONNREFUSED',
  code: 'ESOCKET' } 
It will be retried for the next request.

ConnectionError: Failed to connect to mssql.strongloop.com:1433 - connect ECONNREFUSED
    at Connection.<anonymous> (/Users/moakley/Desktop/Temp/loopback-example-database/node_modules/loopback-connector-mssql/node_modules/mssql/lib/tedious.js:320:25)
    at Connection.g (events.js:180:16)
    at Connection.EventEmitter.emit (events.js:95:17)
    at Connection.socketError (/Users/moakley/Desktop/Temp/loopback-example-database/node_modules/loopback-connector-mssql/node_modules/mssql/node_modules/tedious/lib/connection.js:732:12)
    at Socket.<anonymous> (/Users/moakley/Desktop/Temp/loopback-example-database/node_modules/loopback-connector-mssql/node_modules/mssql/node_modules/tedious/lib/connection.js:3:59)
    at Socket.EventEmitter.emit (events.js:95:17)
    at net.js:440:14
    at process._tickCallback (node.js:415:13)

Update docs for loopback 2.0

Currently the documentation for this example does not work on loopback 2.0 (yeoman is being used instead of slc lb).

Schema discovery, Error: Table 'Account' does not exist.

For some reason, the automigrate.js will work just fine, but the discover-schema.js is not able to find the table, even though it exists in mysql command-line cli and works just fine with the localhost/explorer.

What could be the reason for this?

Full trace:
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/lib/datasource.js:1487:10
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:3694:9
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:359:16
at iteratorCallback (/home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:935:13)
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:843:16
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:3691:13
at apply (/home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:21:25)
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:56:12
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/lib/observer.js:250:22
at doNotify (/home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/lib/observer.js:155:49)
at MySQL.ObserverMixin._notifyBaseObservers (/home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/lib/observer.js:178:5)
at MySQL.ObserverMixin.notifyObserversOf (/home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/lib/observer.js:153:8)
at cbForWork (/home/ubuntu/workspace/mysql-test/node_modules/loopback-datasource-juggler/lib/observer.js:240:14)
at /home/ubuntu/workspace/mysql-test/node_modules/loopback-connector/lib/sql.js:643:7
at handleResponse (/home/ubuntu/workspace/mysql-test/node_modules/loopback-connector-mysql/lib/mysql.js:193:17)
at Query._callback (/home/ubuntu/workspace/mysql-test/node_modules/loopback-connector-mysql/lib/mysql.js:204:7)

Connection fails: Error: Handshake inactivity timeout in loopback

Hi,
I have installed Node.js version 6.9.0 on my machine. I am trying to run sample for SQL database connectivity from examples. I am getting "Connection fails: Error: Handshake inactivity timeout" when i launch application. Unfortunately increasing connectionTimeOut, I am getting same error. my colleagues also facing the same problem with sample https://github.com/strongloop/loopback-example-database/tree/MySQL. please help

regards
arvind

Cannot Get specific file from s3 using Strongloop

Hi @superkhau
I can upload, delete and get list of containers from (s3) but not able to get specific file(path: Mycontainer/folder1/folder2/myFile) from amazon S3 using Strongloop. I am using loopback-datasource-juggler": "^2.7.0. Thanks in advance

My code

$scope.getS3Files = function(myFile){ //have to get all zip files in folder2
  $http.get('api/basePath/containerABC/files/folder1/folder2/' + myFile).then(function (result) {
      $scope.filePath = result.data;
    }, function (err) {
      toastr.error(err.data.error.message);
    }),
  }; 

datasources.json

"dsS3": {
    "name": "dsS3",
    "connector": "loopback-component-storage",
    "provider": "amazon",
    "key": "keyabc",
    "keyId": "keyIdabc"
  },

Error:

message: "Shared class "basePath" has no method handling GET /containerABC/files/folder1/folder2/myFile"
name: "Error"
stack: "Error: Shared class "basePath" has no method handling GET /containerABC/files/folder1/folder2/myFile↵    at restRemoteMethodNotFound (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\strong-remoting\lib\rest-adapter.js:322:17)↵    at Layer.handle [as handle_request] (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\layer.js:95:5)↵    at trim_prefix (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\index.js:312:13)↵    at d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\index.js:280:7↵    at Function.process_params (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\index.js:330:12)↵    at next (d:\NodeJSProjects\abodeadmin\node_modules\loopback\node_modules\express\lib\router\index.js:271:10)↵    at Function.handle (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\index.js:176:3)↵    at router (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\index.js:46:12)↵    at Layer.handle [as handle_request] (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\layer.js:95:5)↵    at trim_prefix (d:\NodeJSProjects\abc\node_modules\loopback\node_modules\express\lib\router\index.js:312:13)"
status: 404
statusCode: 404

Issue in running coffee shop example after connecting to datasource

When I try to run 'node .' after setting up the data source, I get the following log in the terminal:

Browse your REST API at http://localhost:3000/explorer
Connection fails: Error: Handshake inactivity timeout
It will be retried for the next request.
events.js:163z
throw er; // Unhandled 'error' event
^

Error: Handshake inactivity timeout
at Handshake. (/home/ubuntu/loopback-getting-started/node_modules/mysql/lib/protocol/Protocol.js:164:17)
at emitNone (events.js:86:13)
at Handshake.emit (events.js:188:7)
at Handshake._onTimeout (/home/ubuntu/loopback-getting-started/node_modules/mysql/lib/protocol/sequences/Sequence.js:129:8)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)

at Protocol._enqueue (/home/ubuntu/loopback-getting-started/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/home/ubuntu/loopback-getting-started/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at PoolConnection.connect (/home/ubuntu/loopback-getting-started/node_modules/mysql/lib/Connection.js:130:18)
at Pool.getConnection (/home/ubuntu/loopback-getting-started/node_modules/mysql/lib/Pool.js:48:16)
at MySQL.connect (/home/ubuntu/loopback-getting-started/node_modules/loopback-connector-mysql/lib/mysql.js:89:17)
at Object.initializeDataSource [as initialize] (/home/ubuntu/loopback-getting-started/node_modules/loopback-connector-mysql/lib/mysql.js:43:28)
at DataSource.setup (/home/ubuntu/loopback-getting-started/node_modules/loopback-datasource-juggler/lib/datasource.js:417:19)
at new DataSource (/home/ubuntu/loopback-getting-started/node_modules/loopback-datasource-juggler/lib/datasource.js:123:8)
at Registry.createDataSource (/home/ubuntu/loopback-getting-started/node_modules/loopback/lib/registry.js:360:12)
at dataSourcesFromConfig (/home/ubuntu/loopback-getting-started/node_modules/loopback/lib/application.js:512:19)
at Function.app.dataSource (/home/ubuntu/loopback-getting-started/node_modules/loopback/lib/application.js:229:14)
at /home/ubuntu/loopback-getting-started/node_modules/loopback-boot/lib/executor.js:191:9
at /home/ubuntu/loopback-getting-started/node_modules/loopback-boot/lib/executor.js:282:5
at Array.forEach (native)
at forEachKeyedObject (/home/ubuntu/loopback-getting-started/node_modules/loopback-boot/lib/executor.js:281:20)
at setupDataSources (/home/ubuntu/loopback-getting-started/node_modules/loopback-boot/lib/executor.js:181:3)

This example does not conform to the project structure created by the example on the homepage

On the homepage at http://loopback.io/ there is a nice, brief, example of creating a project with model and API explorer.

Structure
site_root/

  • client
  • common
  • node_modules
  • server

However, the example given in this repository does not conform to the same structure which causes confusion when trying to follow an example. It can also lead to non-working examples which is demoralising when working with such a good product.

DELETE method

When using API Explorer everything works fine, but when using Angular SDK none module allow delete method with destroyById() function

loopback:connector:mysql Data: +2ms [ { id: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
ttl: 999999999,
created: Fri Aug 14 2015 02:48:12 GMT+0000 (UTC),
userId: 'XXXXXXXXXXXXXXXXXXXXXXXXXX' } ]
express:router dispatching DELETE /ModelLanguages +0ms
express:router : /spa/ModelLanguages +0ms
express:router : /spa/ModelLanguages +0ms
express:router urlencodedParser : /spa/ModelLanguages +1ms
body-parser:urlencoded skip empty body +0ms
express:router jsonParser : /spa/ModelLanguages +0ms
body-parser:json skip empty body +0ms
express:router trim prefix (/ModelLanguages) from url /ModelLanguages +0ms
express:router router /ModelLanguages : /spa/ModelLanguages +0ms
express:router dispatching DELETE / +0ms
express:router restRemoteMethodNotFound : /spa/ModelLanguages +0ms
express:router restUrlNotFound : /spa/ModelLanguages +1ms
express:router restErrorHandler : /spa/ModelLanguages +0ms
strong-remoting:rest-adapter Error in DELETE /ModelLanguages: Error: Shared class "ModelLanguage" has no method handling DELETE /
at restRemoteMethodNotFound (/var/www/api.io/node_modules/loopback/node_modules/strong-remoting/lib/rest-adapter.js:322:17)
at Layer.handle as handle_request
at trim_prefix (/var/www/api.io/node_modules/loopback/node_modules/express/lib/router/index.js:312:13)
at /var/www/api.apiot.io/node_modules/loopback/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/var/www/api.io/node_modules/loopback/node_modules/express/lib/router/index.js:330:12)
at next (/var/www/api.io/node_modules/loopback/node_modules/express/lib/router/index.js:271:10)
at Function.handle (/var/www/api.io/node_modules/loopback/node_modules/express/lib/router/index.js:176:3)
at router (/var/www/api.io/node_modules/loopback/node_modules/express/lib/router/index.js:46:12)
at Layer.handle as handle_request
at trim_prefix (/var/www/api.io/node_modules/loopback/node_modules/express/lib/router/index.js:312:13) +0ms
compression gzip compression +2ms

Error: Table 'Listing' does not exist.

Hello, just started trying loopback like 4days ago. just have some questions, been trying this but no luck to solve it. :(

the automigrate.js is working fine with me able to create the database and 2 sample data, but not the discover-schema.js and discover-and-build-models.js

here's the error:

/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Parser.js:80
throw err; // Rethrow non-MySQL errors
^

Error: Table 'Listing' does not exist.
at /Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/lib/datasource.js:1540:10
at /Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:3694:9
at /Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:359:16
at iteratorCallback (/Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:935:13)
at /Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:843:16
at /Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:3691:13
at apply (/Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:21:25)
at /Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/node_modules/async/dist/async.js:56:12
at /Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/lib/observer.js:250:22
at doNotify (/Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/lib/observer.js:155:49)
at MySQL.ObserverMixin._notifyBaseObservers (/Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/lib/observer.js:178:5)
at MySQL.ObserverMixin.notifyObserversOf (/Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/lib/observer.js:153:8)
at cbForWork (/Users/zar/test/listing-proj/node_modules/loopback-datasource-juggler/lib/observer.js:240:14)
at /Users/zar/test/listing-proj/node_modules/loopback-connector/lib/sql.js:643:7
at handleResponse (/Users/zar/test/listing-proj/node_modules/loopback-connector-mysql/lib/mysql.js:193:17)
at Query._callback (/Users/zar/test/listing-proj/node_modules/loopback-connector-mysql/lib/mysql.js:204:7)

also when accessing the /explorer, then try to add some data, doesn't work:

{
"error": {
"statusCode": 500,
"name": "Error",
"message": "ER_NO_SUCH_TABLE: Table 'database.acl' doesn't exist",
"code": "ER_NO_SUCH_TABLE",
"errno": 1146,
"sqlMessage": "Table 'database.acl' doesn't exist",
"sqlState": "42S02",
"index": 0,
"sql": "SELECT model,property,accessType,permission,principalType,principalId,id FROM ACL WHERE model='Listing' AND property IN ('create','') AND accessType IN ('WRITE','') ORDER BY id",
"stack": "Error: ER_NO_SUCH_TABLE: Table 'database.acl' doesn't exist\n at Query.Sequence._packetToError (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)\n at Query.ErrorPacket (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)\n at Protocol._parsePacket (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Protocol.js:279:23)\n at Parser.write (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Parser.js:76:12)\n at Protocol.write (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n at Socket. (/Users/zar/test/listing-proj/node_modules/mysql/lib/Connection.js:103:28)\n at emitOne (events.js:96:13)\n at Socket.emit (events.js:188:7)\n at readableAddChunk (_stream_readable.js:176:18)\n at Socket.Readable.push (_stream_readable.js:134:10)\n at TCP.onread (net.js:548:20)\n --------------------\n at Protocol._enqueue (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Protocol.js:145:48)\n at PoolConnection.query (/Users/zar/test/listing-proj/node_modules/mysql/lib/Connection.js:208:25)\n at runQuery (/Users/zar/test/listing-proj/node_modules/loopback-connector-mysql/lib/mysql.js:197:16)\n at executeWithConnection (/Users/zar/test/listing-proj/node_modules/loopback-connector-mysql/lib/mysql.js:239:7)\n at Ping.onOperationComplete [as _callback] (/Users/zar/test/listing-proj/node_modules/mysql/lib/Pool.js:110:5)\n at Ping.Sequence.end (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/sequences/Sequence.js:88:24)\n at Ping.Sequence.OkPacket (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/sequences/Sequence.js:97:8)\n at Protocol._parsePacket (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Protocol.js:279:23)\n at Parser.write (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Parser.js:76:12)\n at Protocol.write (/Users/zar/test/listing-proj/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n at Socket. (/Users/zar/test/listing-proj/node_modules/mysql/lib/Connection.js:103:28)\n at emitOne (events.js:96:13)\n at Socket.emit (events.js:188:7)\n at readableAddChunk (_stream_readable.js:176:18)\n at Socket.Readable.push (_stream_readable.js:134:10)\n at TCP.onread (net.js:548:20)"
}
}

Shared class \"account\" has no method handling GET /

I'm trying to run this demo but is showing this error:

Browser error:
{
"error": {
"name": "Error",
"status": 404,
"message": "Shared class "account" has no method handling GET /",
"statusCode": 404,
"stack": "Error: Shared class "account" has no method handling GET /\n at Object.restRemoteMethodNotFound as handle\n at next (/Users/guiwunsch/Projetos/HereIAmWS/tests/loopback-mysql-example/node_modules/loopback/node_modules/strong-remoting/node_modules/express/node_modules/connect/lib/proto.js:193:15)\n at Object.expressInit as handle\n at next (/Users/guiwunsch/Projetos/HereIAmWS/tests/loopback-mysql-example/node_modules/loopback/node_modules/strong-remoting/node_modules/express/node_modules/connect/lib/proto.js:193:15)\n at Object.query as handle\n at next (/Users/guiwunsch/Projetos/HereIAmWS/tests/loopback-mysql-example/node_modules/loopback/node_modules/strong-remoting/node_modules/express/node_modules/connect/lib/proto.js:193:15)\n at Function.app.handle (/Users/guiwunsch/Projetos/HereIAmWS/tests/loopback-mysql-example/node_modules/loopback/node_modules/strong-remoting/node_modules/express/node_modules/connect/lib/proto.js:201:3)\n at Object.fn as handle\n at next (/Users/guiwunsch/Projetos/HereIAmWS/tests/loopback-mysql-example/node_modules/loopback/node_modules/strong-remoting/node_modules/express/node_modules/connect/lib/proto.js:193:15)\n at next (/Users/guiwunsch/Projetos/HereIAmWS/tests/loopback-mysql-example/node_modules/loopback/node_modules/strong-remoting/node_modules/express/node_modules/connect/lib/proto.js:168:78)"
}
}

Terminal Log:
GET /api/accounts/ 404 3ms - 2.17kb

Can you help me?
Thanks

Error: column "createdat" does not exist

I'm attempting to use a the following model but when I attempt to perform a 'GET' (Find all instances of the model matched by filter from the data source) I get the following response:

{
"error": {
"name": "error",
"status": 500,
"message": "column \"createdat\" does not exist",
"length": 103,
"severity": "ERROR",
"code": "42703",
"position": "101",
"file": "parse_relation.c",
"line": "2655",
"routine": "errorMissingColumn",
"stack": "error: column \"createdat\" does not exist\n    at Connection.parseE (/Users/conner/workspace/cdmcnamara/gatewayd-basic/node_modules/loopback-connector-postgresql/node_modules/pg.js/lib/connection.js:534:11)\n    at Connection.parseMessage (/Users/conner/workspace/cdmcnamara/gatewayd-basic/node_modules/loopback-connector-postgresql/node_modules/pg.js/lib/connection.js:361:17)\n    at Socket.<anonymous> (/Users/conner/workspace/cdmcnamara/gatewayd-basic/node_modules/loopback-connector-postgresql/node_modules/pg.js/lib/connection.js:105:22)\n    at Socket.emit (events.js:95:17)\n    at Socket.<anonymous> (_stream_readable.js:764:14)\n    at Socket.emit (events.js:92:17)\n    at emitReadable_ (_stream_readable.js:426:10)\n    at emitReadable (_stream_readable.js:422:5)\n    at readableAddChunk (_stream_readable.js:165:9)\n    at Socket.Readable.push (_stream_readable.js:127:10)"
}
}

My model is as follows:

{
   "name":"Addresses",
   "options":{
      "idInjection":false,
      "postgresql":{
         "schema":"public",
         "table":"addresses"
      }
   },
   "properties":{
      "id":{
         "type":"Number",
         "required":false,
         "length":null,
         "precision":32,
         "scale":0,
         "id":1,
         "postgresql":{
            "columnName":"id",
            "dataType":"integer",
            "dataLength":null,
            "dataPrecision":32,
            "dataScale":0,
            "nullable":"NO"
         }
      },
      "managed":{
         "type":"Boolean",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"managed",
            "dataType":"boolean",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"NO"
         }
      },
      "address":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"address",
            "dataType":"character varying",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"NO"
         }
      },
      "type":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"type",
            "dataType":"character varying",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"NO"
         }
      },
      "userId":{
         "type":"Number",
         "required":false,
         "length":null,
         "precision":32,
         "scale":0,
         "postgresql":{
            "columnName":"user_id",
            "dataType":"integer",
            "dataLength":null,
            "dataPrecision":32,
            "dataScale":0,
            "nullable":"YES"
         }
      },
      "tag":{
         "type":"Number",
         "required":false,
         "length":null,
         "precision":32,
         "scale":0,
         "postgresql":{
            "columnName":"tag",
            "dataType":"integer",
            "dataLength":null,
            "dataPrecision":32,
            "dataScale":0,
            "nullable":"YES"
         }
      },
      "secret":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"secret",
            "dataType":"character varying",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"YES"
         }
      },
      "previousTransactionHash":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"previous_transaction_hash",
            "dataType":"character varying",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"YES"
         }
      },
      "createdat":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"createdAt",
            "dataType":"timestamp without time zone",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"YES"
         }
      },
      "updatedat":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"updatedAt",
            "dataType":"timestamp without time zone",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"YES"
         }
      },
      "uid":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"uid",
            "dataType":"character varying",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"YES"
         }
      },
      "data":{
         "type":"String",
         "required":false,
         "length":null,
         "precision":null,
         "scale":null,
         "postgresql":{
            "columnName":"data",
            "dataType":"text",
            "dataLength":null,
            "dataPrecision":null,
            "dataScale":null,
            "nullable":"YES"
         }
      }
   },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}

The above model was generated by doing:

var loopback = require('loopback');
var ds = loopback.createDataSource('postgresql', {
  "host": "127.0.0.1",
  "port": 5432,
  "database": "db",
  "username": "user",
  "password": ""
});

ds.discoverSchema('addresses', {}, function(er, schema) {
  console.log(JSON.stringify(schema, null, '  '));
});

I can't seem to figure out why it can't map the createdat column. Thanks in advance for your help.

node create-test-data causes error.

C:\Users\m089269\WebstormProjects\sprint-backend\hello-world>node create-test-data

module.js:340
throw err;
^
Error: Cannot find module 'C:\Users\m089269\WebstormProjects\sprint-backend\hello-world\create-test-data'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

Application simply crashed at starting up time if there is no connectivity from the app to database

When do npm start, if the connection between the host machine and database for some reason not available, the app simply crashed.

<mypath>/nodejs/strongloop/loopback-example-database/node_modules/loopback-connector-mongodb/node_modules/mongodb/lib/mongo_client.js:224
          throw err
          ^
MongoError: failed to connect to server [demo.strongloop.com:27017] on first connect
    at null.<anonymous> (<mypath>/strongloop/loopback-example-database/node_modules/loopback-connector-mongodb/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:326:35)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at null.<anonymous> (<mypath>/strongloop/loopback-example-database/node_modules/loopback-connector-mongodb/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js:270:12)
    at g (events.js:260:16)
    at emitTwo (events.js:87:13)
    at emit (events.js:172:7)
    at Socket.<anonymous> (<mypath>/strongloop/loopback-example-database/node_modules/loopback-connector-mongodb/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:175:49)
    at Socket.g (events.js:260:16)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at connectErrorNT (net.js:996:8)
    at doNTCallback2 (node.js:441:9)
    at process._tickCallback (node.js:355:17)

npm ERR! Darwin 14.5.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v4.2.2
npm ERR! npm  v2.14.7
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `node .`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script 'node .'.
npm ERR! This is most likely a problem with the loopback-example-database package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node .
npm ERR! You can get their info via:
npm ERR!     npm owner ls loopback-example-database
npm ERR! There is likely additional logging output above.

create-test-data.js doesn't work with mysql database

I am sure my dataSource may connect db successfully, and I log the informations to debug the code, and I log the result output at last:
-----------------create-test-data.js content-------------------------
var app = require('./server');
console.log('createdata.......1');
var dataSource = app.dataSources.cduserds;
console.log('createdata.......2');
var Account = app.models.account;
console.log('createdata.......3');
var accounts = [
{ email: "[email protected]",
level: 10,
created: new Date(),
modified: new Date()
}, {
email: "[email protected]",
level: 20,
created: new Date(),
modified: new Date()
} ];
console.log('createdata.......4');
var count = accounts.length;
console.log('count========>'+count);
dataSource.automigrate('account', function (err) {
console.log('createdata.......5');
accounts.forEach(function(act) {
Account.create(act, function(err, result) {
if(!err) {
console.log('Record created:', result);
count--;
if(count === 0) {
console.log('done');
dataSource.disconnect();
}
}
});
console.log('createdata.......6');
});
});

--------------------------------console output---------------------------------------
createdata.......1
createdata.......2
createdata.......3
createdata.......4
count========>2

Ctrl + C does not terminate the process

Hi,
While trying this loopback-exemple-database application, when I hit Ctrl + C, the app looks like terminated but it is not. The process does not get killed and I have to kill it manually. Any idea please?

Web server listening at: http://0.0.0.0:3000
Browse your REST API at http://0.0.0.0:3000/explorer
connectors:oracle is licensed from 2016-01-23T16:19:03.823Z to 2017-01-22T16:19:03.823Z.
^C
:loopback-example-database dn$ lsof -i tcp:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 88062 dn 24u IPv4 0x2e934247acaae9b5 0t0 TCP *:hbci (LISTEN)

Environment:
Mac 10.10.5
Node 4.2.2

disconnection with mongodb server on using mongdb datasource

When I connect 'Review' model of this example to mongodb datasource, this example is disconnected with mongodb server.

mongodb servers' logs are the followings.

2014-12-27T15:52:05.829+0900 [initandlisten] connection accepted from 127.0.0.1:57496 #18 (1 connection now open)
2014-12-27T15:52:05.843+0900 [conn18] end connection 127.0.0.1:57496 (0 connections now open)
2014-12-27T15:52:05.847+0900 [initandlisten] connection accepted from 127.0.0.1:57497 #19 (1 connection now open)
2014-12-27T15:52:05.848+0900 [initandlisten] connection accepted from 127.0.0.1:57498 #20 (2 connections now open)
2014-12-27T15:52:05.848+0900 [initandlisten] connection accepted from 127.0.0.1:57499 #21 (3 connections now open)
2014-12-27T15:52:05.849+0900 [initandlisten] connection accepted from 127.0.0.1:57500 #22 (4 connections now open)
2014-12-27T15:52:05.849+0900 [initandlisten] connection accepted from 127.0.0.1:57501 #23 (5 connections now open)
2014-12-27T15:52:05.853+0900 [conn20] CMD: drop strongloop_test.Customer
2014-12-27T15:52:05.855+0900 [conn21] CMD: drop strongloop_test.Order
2014-12-27T15:52:05.856+0900 [conn22] CMD: drop strongloop_test.Review
2014-12-27T15:52:05.863+0900 [conn19] build index on: strongloop_test.Order properties: { v: 1, key: { _id: 1 }, name: "_id_", ns: "strongloop_test.Order" }
2014-12-27T15:52:05.863+0900 [conn19]    added index to empty collection
2014-12-27T15:52:05.864+0900 [conn20] build index on: strongloop_test.Customer properties: { v: 1, key: { _id: 1 }, name: "_id_", ns: "strongloop_test.Customer" }
2014-12-27T15:52:05.864+0900 [conn20]    added index to empty collection
2014-12-27T15:52:05.865+0900 [conn21] build index on: strongloop_test.Review properties: { v: 1, key: { _id: 1 }, name: "_id_", ns: "strongloop_test.Review" }
2014-12-27T15:52:05.865+0900 [conn21]    added index to empty collection


2014-12-27T15:54:04.810+0900 [initandlisten] connection accepted from 127.0.0.1:57979 #24 (6 connections now open)
2014-12-27T15:55:30.118+0900 [conn23] end connection 127.0.0.1:57501 (5 connections now open)
2014-12-27T15:55:30.118+0900 [conn22] end connection 127.0.0.1:57500 (5 connections now open)
2014-12-27T15:55:30.118+0900 [conn21] end connection 127.0.0.1:57499 (5 connections now open)
2014-12-27T15:55:30.118+0900 [conn20] end connection 127.0.0.1:57498 (5 connections now open)
2014-12-27T15:55:30.118+0900 [conn19] end connection 127.0.0.1:57497 (4 connections now open)

As a result of my debugging, this disconnection has been caused by 15 line of the following code.
I think that 15 line dataSource.disconnect(); should be removed.
After removing this line, everything runs well :)

module.exports = function(server) {
  var dataSource = server.dataSources.db;
  dataSource.automigrate('Review', function(er) {
    if (er) throw er;
    var Model = server.models.Review;
    //create sample data
    var count = reviews.length;
    reviews.forEach(function(review) {
      Model.create(review, function(er, result) {
        if (er) return;
        console.log('Record created:', result);
        count--;
        if (count === 0) {
          console.log('done');
          dataSource.disconnect();
        }
      });
    });
  });
};

Ran through README, API is servering XML

Response for http://127.0.0.1:3000/api/accounts is:

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <result>
    <__persisted>true</__persisted>
    <__cachedRelations/>
    <__data>
      <email>[email protected]</email>
      <created>2014-10-23T23:18:08.207Z</created>
      <modified>2014-10-23T23:18:08.207Z</modified>
      <id>1</id>
    </__data>
    <__dataSource></__dataSource>
    <__strict>false</__strict>
  </result>
  <result>
    <__persisted>true</__persisted>
    <__cachedRelations/>
    <__data>
      <email>[email protected]</email>
      <created>2014-10-23T23:18:08.207Z</created>
      <modified>2014-10-23T23:18:08.207Z</modified>
      <id>2</id>
    </__data>
    <__dataSource></__dataSource>
    <__strict>false</__strict>
  </result>
</response>

I don't see where to specify response data type and from http://docs.strongloop.com/display/LB/Exposing+models+over+a+REST+API it states specirically:

The response format for all requests is a JSON object [...]

Why is it returning XML? How do I get it to return JSON?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.