Connect to MongoDb in NodeJS (latest version 4.0) with Mongoose

Setup project structure

npm init
npm install express --save
npm install mongoose --save

NodeJS with MongoDb

packages.json

{
  "name": "nodejswithmongodb",
  "version": "1.0.0",
  "description": "TranKyPhat Web: NodeJS with MongoDb",
  "main": "app.js",
  "dependencies": {
    "express": "^4.13.3",
    "mongoose": "^4.2.4"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Tran Ky Phat",
  "license": "ISC"
}

app.js

var express = require("express");
var mongoose = require("mongoose");
var http = require('http');
var app = express();

//Connect Db
mongoose.connect("mongodb://@localhost:27017/trankyphattest");

//Routing
app.get("/", function (req, res) {
    res.status(200).send('Hello World');
});

app.get("*", function (req, res) {
    res.status(404).send();
});




//Start server
app.set('port', 3333);

var server = http.createServer(app);
server.listen(3333, function () {
    //Callback success listen
    console.log('App started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});

node app.js

nodejs helloworld

Create new model call Book.js in models folder

nodejs in mongodb

Book.js

You don’t need a id, because by default mongo will add a _id field for identity

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var bookSchema = new Schema({
    title:{
        type: String,
        required:true
    },
    author:{
        type: String,
        required:true
    },
    description:{
        type: String,
        required: false,
        default:""
    },
    createdDate: {
        type: Date,
        required: false
    }
});


//Fire before save a document
bookSchema.pre("save", function(next) {
    var user = this;

    //Set created Date
    if (this.isNew) {
        user.createdDate = new Date;
    }
    
    next();
});

//create your custom methods
bookSchema.methods.myMethod = function(myParam) {
    return myParam;
};

module.exports = mongoose.model('Book', bookSchema);

Add some code to app.js. It show some query to MongoDb

var express = require("express");
var mongoose = require("mongoose");
var http = require('http');
var app = express();

//Book Schema
var Book = require("./models/Book.js");

//Connect Db
mongoose.connect("mongodb://@localhost:27017/trankyphattest");

//Routing
app.get("/", function(req, res) {
    res.status(200).send('Hello World');
});


app.get("/addnewbook/:title", function(req, res) {
    var newBook = new Book({
    	title: req.params.title,
    	description: 'default description',
    	author:'default author'
    });
    newBook.save(function(err){
    	if(err){
    		res.status(500).send(err);
    	}else{
    		res.status(200).send(newBook);
    	}
    });
});

//Get only title and author field
app.get("/listbook", function(req, res){
	Book.find({},'title author', function(error, books){
		res.status(200).send(books);
	});
});

//Get only title and author field
app.get("/findbook/:title", function(req, res) {
    Book.findOne({
        title: req.params.title
    },'title author', function(err, book) {
        //neu chua ton tai thi cho phep tao
        if (!book) {
            res.status(200).send('Book not found');
        } else {
            res.status(200).send(book);
        }
    })
});

app.get("*", function(req, res) {
    res.status(404).send();
});




//Start server
app.set('port', 3333);

var server = http.createServer(app);
server.listen(3333, function() {
    //Callback success listen
    console.log('App started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});

nodejs with mongodb

nodejs with mongodb

Download example code

More examples at: https://gist.github.com/arvis/3357699

find more queries at: http://mongoosejs.com/docs/2.7.x/docs/query.html

NodeJS: Manipulate MongoDb with Mongoose

Category: Uncategorized
0
3396 views

Join the discussion

Your email address will not be published. Required fields are marked *