nodejs: mongoose module and mongodb

The post shows how a nodejs program connects to mongoDB with mongoose module.

version

bash-3.2$ node -v
v8.1.4

init nodejs project

bash-3.2$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (myapp) 
version: (1.0.0) 
description: 
entry point: (index.js) app.js
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/chengyihe/workspace/node/myapp/package.json:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes) 

install mongoose module
By default, npm install modules locally rather than globally. The files related to mongoose module is put under $(pwd)/node_modules directory.

bash-3.2$ npm install mongoose
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN myapp@1.0.0 No description
npm WARN myapp@1.0.0 No repository field.

+ mongoose@4.11.4
added 31 packages in 6.164s
bash-3.2$ ls -l node_modules/
total 0
drwxr-xr-x   82 chengyihe  staff   2788 Jul 27 07:20 async
drwxr-xr-x    7 chengyihe  staff    238 Jul 27 07:20 bluebird
drwxr-xr-x   10 chengyihe  staff    340 Jul 27 07:20 bson
drwxr-xr-x    6 chengyihe  staff    204 Jul 27 07:20 buffer-shims
drwxr-xr-x    8 chengyihe  staff    272 Jul 27 07:20 core-util-is
drwxr-xr-x   15 chengyihe  staff    510 Jul 27 07:20 debug
drwxr-xr-x    8 chengyihe  staff    272 Jul 27 07:20 es6-promise
drwxr-xr-x    9 chengyihe  staff    306 Jul 27 07:20 hooks-fixed
drwxr-xr-x    7 chengyihe  staff    238 Jul 27 07:20 inherits
drwxr-xr-x   10 chengyihe  staff    340 Jul 27 07:20 isarray
drwxr-xr-x   12 chengyihe  staff    408 Jul 27 07:20 kareem
drwxr-xr-x  640 chengyihe  staff  21760 Jul 27 07:20 lodash
drwxr-xr-x   17 chengyihe  staff    578 Jul 27 07:20 mongodb
drwxr-xr-x   23 chengyihe  staff    782 Jul 27 07:20 mongodb-core
drwxr-xr-x   18 chengyihe  staff    612 Jul 27 07:20 mongoose
drwxr-xr-x   16 chengyihe  staff    544 Jul 27 07:20 mpath
drwxr-xr-x   10 chengyihe  staff    340 Jul 27 07:20 mpromise
drwxr-xr-x   12 chengyihe  staff    408 Jul 27 07:20 mquery
drwxr-xr-x    6 chengyihe  staff    204 Jul 27 07:20 ms
drwxr-xr-x   12 chengyihe  staff    408 Jul 27 07:20 muri
drwxr-xr-x    8 chengyihe  staff    272 Jul 27 07:20 process-nextick-args
drwxr-xr-x   19 chengyihe  staff    646 Jul 27 07:20 readable-stream
drwxr-xr-x   11 chengyihe  staff    374 Jul 27 07:20 regexp-clone
drwxr-xr-x   10 chengyihe  staff    340 Jul 27 07:20 require_optional
drwxr-xr-x    6 chengyihe  staff    204 Jul 27 07:20 resolve-from
drwxr-xr-x    8 chengyihe  staff    272 Jul 27 07:20 safe-buffer
drwxr-xr-x    8 chengyihe  staff    272 Jul 27 07:20 semver
drwxr-xr-x    7 chengyihe  staff    238 Jul 27 07:20 sliced
drwxr-xr-x    7 chengyihe  staff    238 Jul 27 07:20 string_decoder
drwxr-xr-x    8 chengyihe  staff    272 Jul 27 07:20 util-deprecate

mongodb client source code
The nodejs example loads mongoose module, connects to a mongoDB server, and then inserts a data satisfied a schema.

  • require(‘mongoose’): it loads mongoose module
  • mongoose.connect(): it connects to a database in a mongoDB server
  • Schema: specify the data structure of document in collection
  • Model: it corresponds to a collection in the connected mongoDB server. The first parameter specifies the collection name, the second one is a schema which specifies the format of documents within the collection
bash-3.2$ cat app.js 
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useMongoClient: true,})

var Schema = mongoose.Schema
var memberSchema = new Schema(
    {
        name: String
    }
)
var member = mongoose.model('member', memberSchema)
var person = new member({ name: 'chengyihe' })

person.save(function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('saved');
    }
});

output of running the mongodb client
Output shows data is saved in mongoDB server successfully.

bash-3.2$ node app.js
(node:54460) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
saved

use mongodb shell to check the result
It shows that the test database’s members collection has a document which is inserted by above example.

bash-3.2$ mongo
MongoDB shell version v3.4.6
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.6
Server has startup warnings:
2017-07-26T20:43:13.356+0800 I CONTROL  [initandlisten]
2017-07-26T20:43:13.357+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-07-26T20:43:13.357+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-07-26T20:43:13.357+0800 I CONTROL  [initandlisten]
2017-07-26T20:43:13.357+0800 I CONTROL  [initandlisten]
2017-07-26T20:43:13.357+0800 I CONTROL  [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
> db.kernels.drop()
true
> show collections
members
> db.members.find()
{ "_id" : ObjectId("597936a8cff68dd4bc0b4c71"), "name" : "chengyihe", "__v" : 0 }
> 

conclusion
The post uses a nodejs with mongoose module to insert data in a mongoDB server. Then, it query the data with mongoDB shell.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: