Using mongoose

1-n, 1-1

First of all, there is a huge difference between relationships in MongoDB and those in SQL based datastores (you need to be clear about this from the get-go).

Relationships in MongoDB are just representations of related data. There is no mechanism which maintains the integrity of these relationships.

What mongoose does with refs is just use the field having the ref option to query the _id field of documents in the referenced collection. This is used for operations like populate (which internally calls findById queries on the target collection and replaces the referenced field with the documents).

This being cleared, you can store one or many IDs for the referenced collection in the field, thus creating one-to-one or one-to-many “relationships”.

Add the event

Open up postman. select POST. In the the url, type in http://localhost/events

In Node express code, we have stated that for post verbs at url /events, we want it to hit create_event function. And create_event function is where we implement getting the data from the body object, and saving it into the database.


Then check the database to verify.

Look at the object id 5a2f3f9b8f4a4a4367dbf59e. We use this as the event id that we will be adding attendees to.

Add attendee(s) to the event (1 to n)

In order to register the attendee, we use postman.
given the route code:

we do the following.

web verb: POST
url: http://localhost/events/5a2f3f9b8f4a4a4367dbf59e

Notice that the last param is a phoneId. We just give a phone number like so:

url: http://localhost/events/5a2f3f9b8f4a4a4367dbf59e/13510083852

When the user put this in the browser, it will hit the registerAttendee function in node express. The registerAttendee function will look for name and phone in its request object’s body:

Hence, as we can see, it gets the properties phone and name from the body, create an object out of it, and pushes it onto the attendees’ array property.

So in your post man, click on body, highlight x-www-form-urlencoded, and enter key/values:

name: Hannah Hong
phone: 135103483252

Essentially, we are entering the properties that are needed by the eventAttendee schema:

Once you press Send on postman, the attendee should be in. Check the database:

> db.funEvents.find()


{ “_id” : ObjectId(“5a2f3f9b8f4a4a4367dbf59e”),
“Event_Title” : “Super Badminton”,
“Event_Description” : “Play some badminton with fellow friends”,
“Author” : “Ricky T”,
“attendees” : [ { “phone” : “135103483252”, “name” : “Hannah Hong”, “registered” : false, “_id” : ObjectId(“5a2f405a8f4a4a4367dbf59f”) } ],
“Created_Date” : ISODate(“2017-12-12T02:31:55.180Z”),
“Event_Location” : null,
“Event_Date” : ISODate(“2017-12-12T02:31:55.180Z”), “__v” : 1 }

You will see that the attendees array now has the user Hannah Hong.

You can add as many users as you like as this is 1 to n. One event, many users.

Adding the location (1 to 1)

Adding the location to our event involves hitting the url at /events/:eventId
with a PUT verb:


We put the event id at the end of the url like so: http://localhost/events/5a2f3f9b8f4a4a4367dbf59e

web verb: PUT
url: http://localhost/events/5a2f3f9b8f4a4a4367dbf59e


We add the information for the location via the body through

body => x-www-form-urlencoded:

address:132 Children’s park, hai yue, Shekou
province: Guangdong
zip: 2847384

hit the “Send” button.

Finally, check your database:

> db.funEvents.find()


{ “_id” : ObjectId(“5a2f3f9b8f4a4a4367dbf59e”),
“Event_Title” : “Super Badminton”,
“Event_Description” : “Play some badminton with fellow friends”,
“Author” : “Ricky T”,
“attendees” : [ { “phone” : “13510083852”, “name” : “Hannah Hong”, “registered” : false, “_id” : ObjectId(“5a2f405a8f4a4a4367dbf59f”) } ],
“Created_Date” : ISODate(“2017-12-12T02:31:55.180Z”),
“Event_Location” : { “_id” : ObjectId(“5a2f4195a713254374cbceee”), “zip” : “2847384”, “province” : “Guangdong”, “city” : “Shenzhen”, “address” : “132 Children’s park, hai yue, Shekou” },
“Event_Date” : ISODate(“2017-12-12T02:31:55.180Z”), “__v” : 1 }

Further References

Installing Mongoose

npm install mongoose –-save

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.



Find all People

Find one person

Removing Users

Using mongo via terminal for DB manipulation

$ mongo

MongoDB shell version: 3.0.4
connecting to: test

> show dbs

bookAPI 0.078GB
local 0.078GB
my_database_name 0.078GB


Don’t worry about “connecting to” … that’s just the default database Mongo decides to use if you don’t specify one on the command line, which we didn’t because it’s not important right now. It doesn’t actually even create the “test” database unless you add a record. It’d be totally fine to just work in that database for right now, but let’s make one of our own. In your Mongo console, type the following:

Now we’re using the database “test1.” Nothing actually exists yet. To make the database exist, we have to add some data. We’re going to start off by doing that right inside of the Mongo client.


MongoDB uses JSON for its structure.

Let’s add a record to our collection. Note that we are currently ‘on’ database test1. So whatever we insert will be into database ‘test1’. Our data format will thus look like this:

Something important to note here: that “db” stands for our database, which as mentioned above we’ve defined as “test1”. The “usercollection” is the name of our collection in this database. Its kind of like ‘table’ in a SQL database. Every JSON we insert is like a row. Note that there wasn’t a step where we created the “usercollection” collection. That’s because the first time we add to it, it’s going to be auto-created. OK, Hit enter. Assuming everything went right, you should see … nothing. That’s not very exciting, so type this:

Showing all data from table

You access the table name by saying ‘db’ for current database, then db.tableName, which in our case is users, so it would be db.users. Finally, we use find() to display all data so in the end it would be:



{ “_id” : ObjectId(“559261a6250879f91747a6a5”), “name” : “MODULUS ADMIN”, “age” : 42, “roles” : [ “admin”, “moderator”, “user” ], “__v” : 0 }

Find where age > “—“

> db.users.find( { age: { $gt: 25 } } )

{ “_id” : ObjectId(“559261a6250879f91747a6a5”), “name” : “MODULUS ADMIN”, “age” : 42, “roles” : [ “admin”, “moderator”, “user” ], “__v” : 0 }

> db.users.find( { age: { $gt: 43 } } )


Clear out a Collection

Removing objects where name is “—“

> db.users.remove({name:”MODULUS ADMIN”})

WriteResult({ “nRemoved” : 1 })

> db.users.find()


counting how many are in a table

> db.users.count()



If the collection does not exist, the insert() method creates the collection.

> db.users.insert( { name: “ricky”, age: 35, roles:”admin” } )

Dropping Collections

db.{collection name}.drop()

Dropping Database

use my_database_name

switched to db my_database_name

> db.dropDatabase()

{ “dropped” : “my_database_name”, “ok” : 1 }

Viewing contents of a database

first show all database

> show dbs;

PersonDatabase 0.078GB
local 0.078GB

Then pick a database to use

> use PersonDatabase;

switched to db PersonDatabase

Then show all collections inside that database

> show collections


Then do db.{collection name}.find()

> db.people.find()

{ “_id” : ObjectId(“55939a0800f3e7343974a41f”), “name” : “Ricky-dude”, “username” : “rtsao”, “password” : “compaq”, “admin” : true, “__v” : 0 }
{ “_id” : ObjectId(“55939adc2b0f71473b38b3d6”), “name” : “Ricky-dude”, “username” : “hadoken”, “password” : “compaq”, “admin” : true, “__v” : 0 }
{ “_id” : ObjectId(“55939b81648f93fd3bb1f4f1”), “name” : “Ricky-dude”, “username” : “shoryuken”, “password” : “compaq”, “admin” : true, “__v” : 0 }

inserting dates via terminal

db.badmintonEvents.insert({ “attendee_name” : “badminton_2-18-2016”, “date” : ISODate(“2016-02-18T00:00:00Z”), “description” : “8:00pm at baishizhou” })

Using Gulp and Nodemon

npm init

then insert project info

npm install express

touch app.js

Let’s install it where it save info into the project json file:

npm install gulp –save
npm install gulp -g
npm install gulp-nodemon

for using nodemon to restart the server whenever you make a change:

npm install -g nodemon

Installing nodemon basically means you can start your server like so:
“nodemon app.js”,
and whenever you save a change, it will restart your server for you.

Go to your root directory, then create a file called gulpfile.js with the code like below:

touch gulpfile.js

shortcut for starting your server

Whenever you run the project, usually people would do “node app.js”. But it can get annoying. So instead, we can shortcut it with start. So next time, all you gotta do to start the server is to type: npm start.

Remeber to use nodemon app.js as the command. Or else, you won’t get the capabilities of nodemon.

So now, you can simply go npm start, and your server will start.

Install MongoDB on Mac

ref –

Moving files

First download the mongo database file from its website. Be default, your mac should put it into your ~/Download folder. Then open up a terminal.

You cd into the download directory. Then you unzip the tgz file. Then you move the folder into directory /usr/local/mongdb

cd ~/Download
$ tar xzf mongodb-osx-x86_64-2.2.3.tgz
$ sudo mv mongodb-osx-x86_64-2.2.3 /usr/local/mongodb

You should now see the mongodb folder with bin and data in the directory /usr/local/mongdb.

data/db folder

By default, MongoDB write/store data into the /data/db folder, you need to create this folder manually and assign proper permission. We make the directory, then check who the current User is. Then give permission to the current user for directory /data/db

$ sudo mkdir -p /data/db
$ whoami


$ sudo chown rickytsao /data/db

Now, the directory /data/db is ready for mongodb data writes.

.bash_profile file

Now we need to open up our .bash_profile and add a PATH entry. This is so that we can run mongod, and mongo from the /usr/local/mongodb/bin directory without having to type out the whole path.

$ cd ~
$ pwd
$ touch .bash_profile
$ vim .bash_profile

Then type in the following into the .bash_profile file:

export MONGO_PATH=/usr/local/mongodb

restart terminal, then:

$ mongo -version

MongoDB shell version: 2.2.3

In terminal 1:

$ mongod

MongoDB starting : pid=34022 port=27017 dbpath=/data/db/ 64-bit host=mkyong.local
waiting for connections on port 27017

In terminal 2:

$ mongo

MongoDB shell version: 2.2.3
connecting to: test

> show dbs

local (empty)

If you happen to get a “rlimits warning”, just type just type “ulimit -n 2048” or use something higher.

Using Mongoose

npm install mongoose –save


“article” is related to “section”, but is distinctly different. Whereas

is for grouping distinct sections of content or functionality,

is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way – if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then “article” is suitable for marking them up.

In our example,

contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore “article” is perfect for them:

like so:


In short, a header typically contains at least (but not restricted to) one heading tag (h1 – h6).

Figure and figcaption


An easy smell test is would this make sense in an RSS feed? Of course weblog articles and static pages would make sense in a feed reader,

  • Break mechanical cab driver.
  • Drive to abandoned factory
  • Watch video of self

some copyright print for this site heheheh

Writing own middleware module

Standard files




Writing custom middleware

use request.url and request.method to get request info

The response object emits events, including ‘finish’. Which means that the response has been handed off to you.

Use next() to go on to the next middleware layer:

Basically whenever you’ve included your middleware module, you make it run


basic JSON data movement via node and express

install express

You will then see node_modules folder in your project directory. Inside node_modules, you’ll see express framework folder. You are now ready to use express.

In your project directory, create an app.js file.

Then use require function to load in the express library:

Then get the application instance by calling express().
After that let’s designate the folder ‘public’ to be static and serve up web pages from there. We place all web pages into the ‘public’ folder from now on.

Finally, we use function ‘get’ to receive GET events and then have a handler to process that GET event. In our case, we simply create a local array on the stack…and simply throw it back with the response object.

app.js code

public/index.html code

Create a public folder in your project directory. Throw in the image blocks.png. Then create index.html and Put in the code below:

Basically, we check to see if jQuery library is loaded. We then load in the block.png image and also load in client.js file.


This javascript is embedded in the index.html file. Once the page loads, we use jQuery’s

method to load data from the server using HTTP GET request. It requests the url ‘/blocks’ from the server, and uses the appendToList function to process whatever data comes back with the response object.

When it comes back…we create an empty array, and fill it with the data from the response object. For every index i in blocks, we get the text and wrap it inside of li tags. Then push it onto our empty array.

Finally, we have our ul .block-list add the list of li tags.

client.js code

Run it

Go into the project directory where app.js and folders public, node_modules are, and in your terminal go:

node app.js

Then open a browser and


You will see that it runs the code in our html from top to down…including our client.js

The client.js will trigger the GET event call towards the browser which will return an array of words to our page. Then It puts the text into li tags, and in turn appends the list of li tags onto a ul tag to be displayed on the browser.

Create secure connection with Server using Certificate, ios

You are trying to communicate with a server via a client app.

Transport Layer Security (TLS), formerly Secure Sockets Layer (SSL), is the standard for encrypting and authenticating messages and identifying users and servers. Using TLS, you can be sure that the Server to which you are connected is the one intended, that no one sees the contents of your messages, and that the Server can verify that the contents they received is the one that you sent.

So given that we have an iOS client app, the server side will provide you with a .crt file.

You will need a DER-encoded X.509 public certificate in your app. The first step is to convert the .crt file to the .der file. Download the .crt file onto your desktop like so:

Rickys-MacBook-Pro:Desktop rickytsao$ openssl x509 -in loadhigh.crt -outform der -out “trusted_cert.der”

In our example, its called loadhigh.crt

Then run

to convert the crt file to der.

Then, put the .DER encoded certificate into the bundle.

How to create a bundle

Create a folder in finder
Add the .der file to the folder
Rename the folder so that its extension is .bundle (e.g. “New folder” -> “YonoAssets.bundle”)

PS: You can at any time right click the folder and hit “Show package content” in order to add, remove or modify any of the files. Drag it into you project

<3>How to use the bundle

debugging with xCode (pt 5) – conditional debugging


As you’re debugging your app, it may take in user input, for example, a gift name that’s a string.

Hence, code wise we want to say “if is equal to ‘xbox'”.

If you want to break whenever this string is equal to say “xbox”, you can do so using conditional debugging.

Edit the breakpoint and at the Condition textbox input the code:

The expression must evaluate to something so we simply cast it to BOOL.

Now, if you were to go back to your app and input xbox into the textfield, the runtime compiler will break to this line.


So now that the user have just entered “xbox”, we reach to this breakpoint. Let’s say we want to set this variable to something else instead, say “ps3”.

You simply add in an Action with the Debugger Command and insert the expression:

Again, we’re telling the debugger this is an expression and thus must evaluate to something. Since its a set command, we just cast it void.

Therefore, we’re basically saying if the user enters a string that matches “xbox”, we want to change to “ps3” instead.


use the code’s setter method to set to ps3 in Action >> Debugger Command‘s textfield


Now when you start the app and input “xbox”, it’ll jump to that breakpoint. While the program is paused, in your variable section, right click and select “Add Expression”. Put


Then, have the debugger step down 1 line (fn + F6) so that you process the line of code. In your variable section, you will see that our expression was indeed changed to “ps3”.