I am trying to build a Node API which uses MongoDB to create and fetch information from a file which contains Book information in the following JSON format:
{
Name: String,
Author: String,
Price: Number
}
I am unable to add info to the DB. I get the Book printed successfully message though. But when I see the DB, a JSON document is created only with an ID and the version key _v.
Below is my API code:
var express = require('express');
var app = express();
var bodyParser=require('body-parser');
var mongoose=require('mongoose');
var book = require('./automobile/reading/book')
//configuring the app for the bosy data intake for post operations
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
var PORT= process.env.PORT || 3000;
mongoose.connect('mongodb://localhost:27017/helloworldapi');
var router = express.Router();
app.use('/api', router);
router.use(function(req,res,next){
console.log('There is something happening in the API');
next();
})
router.route('/books')
.post(function(req,res){
var bookDB = new book();
bookDB.name=req.body.name;
bookDB.author=req.body.author;
bookDB.price=req.body.price;
bookDB.save(function(err){
if(err){
res.send(err);
}
res.json({message: 'Book was successfully printed'});
});
})
.get(function(req,res){
book.find(function(err, books){
if(err){
res.send(err);
}
res.json(books);
});
});
router.route('/books/:book_id')
.get(function(req,res){
book.findById(req.params.book_id, function(err, books){
if(err){
res.send(err);
}
res.json(books)
});
});
router.route('/books/name/:name')
.get(function(req,res){
book.find({name:req.params.name}, function(err, books){
if(err){
res.send(err);
}
res.json(books);
});
});
router.route('/books/author/:author')
.get(function(req,res){
book.find({author:req.params.author}, function(err, books){
if(err){
res.send(err);
}
res.json(books);
});
});
app.listen(PORT);
console.log('server listening on port '+PORT);
While trying to perform a GET Operation after performing the POST Operation, I am getting the below response:
[
{
"_id": "5a788cf1ad829e3aa4b91287",
"__v": 0
}
]
Below is my shema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
Name: String,
Author: String,
Price: Number
});
module.exports= mongoose.model('book',BookSchema);
Please don't mind the root folder automobiles. Planned to create something else in the beginning.
You can use
router.route('/books')
.post(function(req,res){
var bookDB = new book(req.body);
bookDB.save(function(err){
if(err){
res.send(err);
}
res.json({message: 'Book was successfully printed'});
});
})
But the req.body values should be same on schema values.
I believe it is because you are not assigning to the right properties. In your route, you assign to the lowercase properties. However, you Schema defines uppercase properties. See if matching the case works:
router.route('/books')
.post(function(req,res){
var bookDB = new book();
bookDB.name=req.body.name; // This needs to match the property in the schema exactly
bookDB.author=req.body.author;
bookDB.price=req.body.price;
bookDB.save(function(err){
if(err){
res.send(err);
}
res.json({message: 'Book was successfully printed'});
});
})
var BookSchema = new Schema({
name: String, // Now I'm lower case
author: String,
price: Number
});
Or you can make your router uppercase:
router.route('/books')
.post(function(req,res){
var bookDB = new book();
bookDB.Name=req.body.name;
bookDB.Author=req.body.author;
bookDB.Price=req.body.price;
bookDB.save(function(err){
if(err){
res.send(err);
}
res.json({message: 'Book was successfully printed'});
});
})
Related
How do you implement MongoDB's Schema Validation feature in Express server? I'm working on a simple todo app and decided to use the native MongoClient instead of mongoose but i still do want to have a schema.
Base on MongoDB's docs here: https://docs.mongodb.com/manual/core/schema-validation/#schema-validation You can either create a collection with Schema or update an existing collection without schema to have one. The commands are run in the mongo shell, but how do you implement it in express?
So far what i did is make a function that returns the Schema Validation commands and call it on every routes but i get an error saying db.runCommand is not a function.
Here's my express server:
const express = require("express");
const MongoClient = require("mongodb").MongoClient;
const ObjectID = require("mongodb").ObjectID;
const dotenv = require('dotenv').config();
const todoRoutes = express.Router();
const cors = require("cors");
const path = require("path");
const port = process.env.PORT || 4000;
const dbName = process.env.DB_NAME;
let db;
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
MongoClient.connect(process.env.MONGO_URI,{useNewUrlParser: true},(err,client)=>{
if(err){
throw err;
console.log(`Unable to connect to the databse: ${err}`);
} else {
db = client.db(dbName);
console.log('Connected to the database');
}
});
/* Schema Validation Function */
const runDbSchemaValidation = function(){
return db.runCommand( {
collMod: "todos",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "description", "responsible","priority", "completed" ],
properties: {
description: {
bsonType: "string",
description: "must be a string and is required"
},
responsibility: {
bsonType: "string",
description: "must be a string and is required"
},
priority: {
bsonType: "string",
description: "must be a string and is required"
},
completed: {
bsonType: "bool",
description: "must be a either true or false and is required"
}
}
} },
validationLevel: "strict"
} );
}
/* Get list of Todos */
todoRoutes.route('/').get((req,res)=>{
runDbSchemaValidation();
db.collection("todos").find({}).toArray((err,docs)=>{
if(err)
console.log(err);
else {
console.log(docs);
res.json(docs);
}
});
});
/* Get Single Todo */
todoRoutes.route('/:id').get((req,res)=>{
let todoID = req.params.id;
runDbSchemaValidation();
db.collection("todos").findOne({_id: ObjectID(todoID)}, (err,docs)=>{
if(err)
console.log(err);
else {
console.log(docs);
res.json(docs);
}
});
});
/* Create Todo */
todoRoutes.route('/create').post((req,res,next)=>{
const userInput = req.body;
runDbSchemaValidation();
db.collection("todos").insertOne({description:userInput.description,responsible:userInput.responsible,priority:userInput.priority,completed:false},(err,docs)=>{
if(err)
console.log(err);
else{
res.json(docs);
}
});
});
/* Edit todo */
todoRoutes.route('/edit/:id').get((req,res,next)=>{
let todoID = req.params.id;
runDbSchemaValidation();
db.collection("todos").findOne({_id: ObjectID(todoID)},(err,docs)=>{
if(err)
console.log(err);
else {
console.log(docs);
res.json(docs);
}
});
});
todoRoutes.route('/edit/:id').put((req,res,next)=>{
const todoID = req.params.id;
const userInput = req.body;
runDbSchemaValidation();
db.collection("todos").updateOne({_id: ObjectID(todoID)},{ $set:{ description: userInput.description, responsible: userInput.responsible, priority: userInput.priority, completed: userInput.completed }},{returnNewDocument:true},(err,docs)=>{
if(err)
console.log(err);
else
res.json(docs);
console.log(db.getPrimaryKey(todoID));
});
});
/* Delete todo */
todoRoutes.route('/:id').delete((req,res,next)=>{
const todoID = req.params.id;
runDbSchemaValidation();
db.collection("todos").deleteOne({_id: ObjectID(todoID)},(err,docs)=>{
if(err)
console.log(err)
else{
res.json(docs);
}
});
});
app.use('/todos',todoRoutes);
app.listen(port,()=>{
console.log(`Server listening to port ${port}`);
});
I also tried it on the initial client connection but i got the same error:
You validation schema will be added to the MongoDB driver when you run it for the first time. So you don't need to perform validation every time you run a query. You will get a validation response directly from the driver's validation schema that was added initially. Again you will not explicitly get to know which object is causing the error. The validation response will be more generic.
I am trying to write a REST backend using Node.js, express and MongoDB but am having some issues creating PUT calls for some reason. The issue is with app.post('/contacts/add', contacts.addContacts) as it works fine if I change it to GET but when I change it to either PUT or POST I get the error Cannot GET /contacts/add Any ideas?
I am using express 4.15.3, mongodb 3.4.5 and npm 4.2.0
server.js:
var express = require('express'),
contacts = require('./routes/contacts');
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/contacts/chalkboard/:id', contacts.getChalkboardContacts);
app.get('/contacts/get/:uid', contacts.getContacts);
app.post('/contacts/add', contacts.addContacts);
app.listen(3000);
console.log('Listening on port 3000...');
contacts.js
var mongo = require('mongodb');
mongo.BSONPure = require('bson').BSONPure;
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('db', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.collection('contacts', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'contacts' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.getChalkboardContacts = function(req, res) {
var uid = req.params.uid.toString();
var date = new Date();
var timeInMs = date.getMilliseconds();
console.log(uid);
db.collection('contacts', function(err, collection) {
console.log('collection: ' + collection);
collection.find({uid: uid, lastMessage: {$gte: timeInMs}}).toArray(function(err, items) {
res.send(items);
});
});
};
exports.getContacts = function(req, res) {
var uid = req.params.uid.toString();
console.log(uid);
db.collection('contacts', function(err, collection) {
console.log('collection: ' + collection);
collection.find({uid: uid}).toArray(function(err, items) {
res.send(items);
});
});
};
exports.addContacts = function(req, res) {
console.log('working');
db.collection('contacts', function(err, collection) {
var id = "592159bc3e48764418170399";
var contact = {uid: "592159bc3e48764418173333",
keyUid: "592159bc3e48764418171444",
name: "Billy Jean",
phoneNumber: "+491721894733",
battery: "47%", longitude: "0",
latitude: "0",
city: "city",
country: "country",
place: "place",
address: "address",
lastMessage: "lastMessage",
lastUpdated: "lastUpdated"};
collection.update({'uid':id}, {$push:{'contacts':contact}}, function(err, result) {
if (err) {
console.log('Error updating contact: ' + err);
res.send({'error':'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(result);
}
});
});
};
I didn't spot anything immediately wrong with the code.
You might be falling into a very common pitfall when using body-parser for JSON. Your request must specify Content-Type: application/json in the request for the parser to parse it. Otherwise, it won't work.
If that doesn't do the trick, if you can share any error messages or response codes you get, it may illuminate another issue.
I'm trying to display mongodb data in my html page. I've already managed to insert data in db but for some reason my "get" function does not work.
I'm using node.js with express framework and Angular for front-end and routing.
This is my "get" function to retreive data from MongoDB:
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
res.render('index', {items: resultArray});
});
});
});
And my "post" which works
router.post('/insert', function(req, res, next) {
var item = {
name: req.body.name,
adress: req.body.adress,
postal: req.body.postal,
city: req.body.city,
email: req.body.email,
phone: req.body.phone,
quotation: req.body.quotation,
message: req.body.message
};
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
});
res.redirect('/contact');
});
i am not sure if this is the correct way to open and close mongo connection each time you are trying to query .
if you want to go for another approach then use mongoose
and follow something like this
https://pastebin.com/g7aatzzj
I think that you have a mistake in your .find().forEach function callbacks. The error handling seems to be in the endCallback not the iteratorCallback.
According to the official doc, the correct way should be :
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find({});
cursor.forEach(function(doc){
assert.notEqual(null, doc);
resultArray.push(doc);
}, function(err, doc){
assert.equal(null, err);
db.close();
res.render('index', {items: resultArray});
});
});
});
This can also be found in their unit tests
var cursor = collection.find({})
.map(function(x) { return {a:1}; })
.batchSize(5)
.limit(10);
cursor.forEach(function(doc) {
test.equal(1, doc.a);
}, function(err, doc) {
test.equal(null, err);
db.close();
test.done();
});
I think that you must have a error that is not passed to the first callback and not handled in the second one. So you do not see the error.
Try to insert an empty object to the find() function as following:
var cursor = db.collection('user-data').find({});
I have just run your code and modified it a bit for my purposes.
Please find the following snippet
//Instantiate MongoClient
var mongo = require('mongodb').MongoClient;
//Assert library (Perhaps overkill if you are writing production-level code)
var assert = require('assert');
//Express engine
var express = require('express');
//URL for my mongo instance
//Connecting to the blog database
var url = 'mongodb://localhost:27017/blog';
//Instantiate express
var router = express();
//Get operation
router.get('/get', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('posts').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
//I have no index file to render, so I print the result to console
//Also send back the JSON string bare through the channel
console.log(resultArray);
res.send(resultArray);
});
});
});
//Start listeninig
//Hardcoded port 1000
var server = router.listen(1000, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
Therefore to get this working for you:
Change the url to 'mongodb://localhost:27017/loodgieters';
Change router to '/get-data'
I hope this helps!
Also consider using splitting the implementation of the get operation to another module to help for the Separation of Responsibilities to make your code more robust.
I am currently attempting to create a .post function for a schema with document reference. However, I am not sure how I can retrieve the ObjectID of the document reference from another collection.
Board.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
boardname: String,
userid: {type: Schema.ObjectId, ref: 'UserSchema'}
});
module.exports = mongoose.model('Board', BoardSchema);
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String
});
module.exports = mongoose.model('User', UserSchema);
routes.js
router.route('/boards')
.get(function(req, res) {
Board.find(function(err, boards) {
if(err)
res.send(err);
res.json(boards);
});
})
.post(function(req, res) {
var board = new Board();
board.boardname = req.body.boardname;
User.find({username: req.body.username}, function(err, user) {
if(err)
res.send(err);
board.userid = user._id;
});
board.save(function(err) {
if(err)
res.send(err);
res.json({message: 'New Board created'});
});
});
To create the board, I include a boardname and a username in my request. Using the username, I do a User.find to find the specific user and assign it to board.userid. However, this does not seem to be working as board.userid does not appear.
Any help would be greatly appreciated!
Thank you!
EDIT
A better explanation of what is required is that I have an existing User collection. When I want to add a new document to Board, I would provide a username, from which I would search the User collection, obtain the ObjectId of the specific user and add it as userid to the Board document.
I believe you are looking for population
There are no joins in MongoDB but sometimes we still want references
to documents in other collections. This is where population comes in.
Try something like this:
//small change to Board Schema
var BoardSchema = new Schema({
boardname: String,
user: {type: Schema.ObjectId, ref: 'User'}
});
//using populate
Board.findOne({ boardName: "someBoardName" })
.populate('user') // <--
.exec(function (err, board) {
if (err) ..
console.log('The user is %s', board.user._id);
// prints "The user id is <some id>"
})
Sorry, I solved a different problem previously. You'll probably want to use the prevoius solution I provided at some point, so I'm leaving it.
Callbacks
The reason the userid is not on the board document is because User.find is asynchronous and is not assigned at the moment board.save(...) is called.
This should do the trick:
(Also, I added a couple of returns to prevent execution after res.send(...))
.post(function(req, res) {
var board = new Board();
board.boardname = req.body.boardname;
User.find({username: req.body.username}, function(err, user) {
if(err)
return res.send(err); //<-- note the return here!
board.userid = user._id;
board.save(function(err) {
if(err)
return res.send(err); //<-- note the return here!
res.json({message: 'New Board created'});
});
});
});
I'm building a node.js app that is a REST api using express and mongoose for my mongodb. I've got the CRUD endpoints all setup now, but I was just wondering two things.
How do I expand on this way of routes, specifically, how do I share modules between routes. I want each of my routes to go in a new file, but obviously only one database connection as you can see i've included mongoose at the top of people.js.
Do I have to write out the schema of the model 3 times in my people.js? The first schema defines the model, then I list all the vars out in the createPerson and updatePerson functions. This feels like how I made php/mysql CRUD back in the day lol. For the update function, I've tried writing a loop to loop through "p" to auto detect what fields to update, but to no avail. Any tips or suggestions would be great.
Also, I'd love any opinions on the app as a whole, being new to node, it's hard to know that the way you are doing something is the most efficient or "best" practice. Thanks!
app.js
// Node Modules
var express = require('express');
app = express();
app.port = 3000;
// Routes
var people = require('./routes/people');
/*
var locations = require('./routes/locations');
var menus = require('./routes/menus');
var products = require('./routes/products');
*/
// Node Configure
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
});
// Start the server on port 3000
app.listen(app.port);
/*********
ENDPOINTS
*********/
// People
app.get('/people', people.allPeople); // Return all people
app.post('/people', people.createPerson); // Create A Person
app.get('/people/:id', people.personById); // Return person by id
app.put('/people/:id', people.updatePerson); // Update a person by id
app.delete('/people/:id', people.deletePerson); // Delete a person by id
console.log('Server started on port ' + app.port);
people.js
//Database
var mongoose = require("mongoose");
mongoose.connect('mongodb://Shans-MacBook-Pro.local/lantern/');
// Schema
var Schema = mongoose.Schema;
var Person = new Schema({
first_name: String,
last_name: String,
address: {
unit: Number,
address: String,
zipcode: String,
city: String,
region: String,
country: String
},
image: String,
job_title: String,
created_at: { type: Date, default: Date.now },
active_until: { type: Date, default: null },
hourly_wage: Number,
store_id: Number, // Inheirit store info
employee_number: Number
});
var PersonModel = mongoose.model('Person', Person);
// Return all people
exports.allPeople = function(req, res){
return PersonModel.find(function (err, person) {
if (!err) {
return res.send(person);
} else {
return res.send(err);
}
});
}
// Create A Person
exports.createPerson = function(req, res){
var person = new PersonModel({
first_name: req.body.first_name,
last_name: req.body.last_name,
address: {
unit: req.body.address.unit,
address: req.body.address.address,
zipcode: req.body.address.zipcode,
city: req.body.address.city,
region: req.body.address.region,
country: req.body.address.country
},
image: req.body.image,
job_title: req.body.job_title,
hourly_wage: req.body.hourly_wage,
store_id: req.body.location,
employee_number: req.body.employee_number
});
person.save(function (err) {
if (!err) {
return res.send(person);
} else {
console.log(err);
return res.send(404, { error: "Person was not created." });
}
});
return res.send(person);
}
// Return person by id
exports.personById = function (req, res){
return PersonModel.findById(req.params.id, function (err, person) {
if (!err) {
return res.send(person);
} else {
console.log(err);
return res.send(404, { error: "That person doesn't exist." });
}
});
}
// Delete a person by id
exports.deletePerson = function (req, res){
return PersonModel.findById(req.params.id, function (err, person) {
return person.remove(function (err) {
if (!err) {
return res.send(person.id + " deleted");
} else {
console.log(err);
return res.send(404, { error: "Person was not deleted." });
}
});
});
}
// Update a person by id
exports.updatePerson = function(req, res){
return PersonModel.findById(req.params.id, function(err, p){
if(!p){
return res.send(err)
} else {
p.first_name = req.body.first_name;
p.last_name = req.body.last_name;
p.address.unit = req.body.address.unit;
p.address.address = req.body.address.address;
p.address.zipcode = req.body.address.zipcode;
p.address.city = req.body.address.city;
p.address.region = req.body.address.region;
p.address.country = req.body.address.country;
p.image = req.body.image;
p.job_title = req.body.job_title;
p.hourly_wage = req.body.hourly_wage;
p.store_id = req.body.location;
p.employee_number = req.body.employee_number;
p.save(function(err){
if(!err){
return res.send(p);
} else {
console.log(err);
return res.send(404, { error: "Person was not updated." });
}
});
}
});
}
I have taken another approach here. Not saying it is the best, but let me explain.
Each schema (and model) is in its own file (module)
Each group of routes for a particular REST resource are in their own file (module)
Each route module just requires the Mongoose model it needs (only 1)
The main file (application entry point) just requires all route modules to register them.
The Mongo connection is in the root file and is passed as parameter to whatever needs it.
I have two subfolders under my app root - routes and schemas.
The benefits of this approach are:
You only write the schema once.
You do not pollute your main app file with route registrations for 4-5 routes per REST resource (CRUD)
You only define the DB connection once
Here is how a particular schema file looks:
File: /schemas/theaterSchema.js
module.exports = function(db) {
return db.model('Theater', TheaterSchema());
}
function TheaterSchema () {
var Schema = require('mongoose').Schema;
return new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
address: { type: String, required: true },
latitude: { type: Number, required: false },
longitude: { type: Number, required: false },
phone: { type: String, required: false }
});
}
Here is how a collection of routes for a particular resource looks:
File: /routes/theaters.js
module.exports = function (app, options) {
var mongoose = options.mongoose;
var Schema = options.mongoose.Schema;
var db = options.db;
var TheaterModel = require('../schemas/theaterSchema')(db);
app.get('/api/theaters', function (req, res) {
var qSkip = req.query.skip;
var qTake = req.query.take;
var qSort = req.query.sort;
var qFilter = req.query.filter;
return TheaterModel.find().sort(qSort).skip(qSkip).limit(qTake)
.exec(function (err, theaters) {
// more code
});
});
app.post('/api/theaters', function (req, res) {
var theater;
theater.save(function (err) {
// more code
});
return res.send(theater);
});
app.get('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
// more code
});
});
app.put('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
// more code
});
});
app.delete('/api/theaters/:id', function (req, res) {
return TheaterModel.findById(req.params.id, function (err, theater) {
return theater.remove(function (err) {
// more code
});
});
});
};
And here is the root application file, which initialized the connection and registers all routes:
File: app.js
var application_root = __dirname,
express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
http = require('http');
var app = express();
var dbProduction = mongoose.createConnection('mongodb://here_insert_the_mongo_connection_string');
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use('/images/tmb', express.static(path.join(application_root, "images/tmb")));
app.use('/images/plays', express.static(path.join(application_root, "images/plays")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.get('/api', function (req, res) {
res.send('API is running');
});
var theatersApi = require('./routes/theaters')(app, { 'mongoose': mongoose, 'db': dbProduction });
// more code
app.listen(4242);
Hope this was helpful.
I found this StackOverflow post very helpful:
File Structure of Mongoose & NodeJS Project
The trick is to put your schema into models directory. Then, in any route, you can require('../models').whatever.
Also, I generally start the mongoose db connection in app.js, and only start the Express server once the connection is up:
mongoose.connect('mongodb://localhost/whateverdb')
mongoose.connection.on('error', function(err) {
console.log("Error while connecting to MongoDB: " + err);
process.exit();
});
mongoose.connection.on('connected', function(err) {
console.log('mongoose is now connected');
// start app here
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
I'd take a look at this project https://github.com/madhums/node-express-mongoose-demo . It is a great example on how to build a nodejs application in a standard way.