Skip to content

Instantly share code, notes, and snippets.

@ccoenraets
Last active November 29, 2022 01:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save ccoenraets/3819468 to your computer and use it in GitHub Desktop.
Save ccoenraets/3819468 to your computer and use it in GitHub Desktop.
var express = require('express'),
wine = require('./routes/wines');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);
app.listen(3000);
console.log('Listening on port 3000...');
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('winedb', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'winedb' database");
db.collection('wines', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving wine: ' + id);
db.collection('wines', function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.findAll = function(req, res) {
db.collection('wines', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.addWine = function(req, res) {
var wine = req.body;
console.log('Adding wine: ' + JSON.stringify(wine));
db.collection('wines', function(err, collection) {
collection.insert(wine, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
exports.updateWine = function(req, res) {
var id = req.params.id;
var wine = req.body;
console.log('Updating wine: ' + id);
console.log(JSON.stringify(wine));
db.collection('wines', function(err, collection) {
collection.update({'_id':new BSON.ObjectID(id)}, wine, {safe:true}, function(err, result) {
if (err) {
console.log('Error updating wine: ' + err);
res.send({'error':'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(wine);
}
});
});
}
exports.deleteWine = function(req, res) {
var id = req.params.id;
console.log('Deleting wine: ' + id);
db.collection('wines', function(err, collection) {
collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred - ' + err});
} else {
console.log('' + result + ' document(s) deleted');
res.send(req.body);
}
});
});
}
/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {
var wines = [
{
name: "CHATEAU DE SAINT COSME",
year: "2009",
grapes: "Grenache / Syrah",
country: "France",
region: "Southern Rhone",
description: "The aromas of fruit and spice...",
picture: "saint_cosme.jpg"
},
{
name: "LAN RIOJA CRIANZA",
year: "2006",
grapes: "Tempranillo",
country: "Spain",
region: "Rioja",
description: "A resurgence of interest in boutique vineyards...",
picture: "lan_rioja.jpg"
}];
db.collection('wines', function(err, collection) {
collection.insert(wines, {safe:true}, function(err, result) {});
});
};
@2color
Copy link

2color commented Dec 25, 2012

I added the missing semi-colons in my fork: https://gist.github.com/4374747

@codele
Copy link

codele commented Apr 28, 2013

UTF-8 support?

@pathtrk
Copy link

pathtrk commented Feb 10, 2014

Hi, Just forked this gist and modified it to use mongoose.

@goshlanguage
Copy link

Hey there,

It looks like mongo has changed a bit since this article, but this article has really helped me. Thank you for writing it.

When I run this, I keep running into the following error when inserting a new record:

[ryan@centos beard]$ curl -i -X POST -H 'Content-Type: application/json' -d '{"name": "test"}' http://localhost:8080/servers
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Content-Type: text/html
Content-Length: 986
Date: Wed, 26 Mar 2014 17:35:50 GMT
Connection: keep-alive

TypeError: Cannot read property '_id' of undefined
at insertAll (/home/ryan/source/node/beard/node_modules/mongodb/lib/mongodb/collection/core.js:174:13)
at Collection.insert (/home/ryan/source/node/beard/node_modules/mongodb/lib/mongodb/collection/core.js:35:3)
at /home/ryan/source/node/beard/routes/servers.js:48:16
at Db.collection (/home/ryan/source/node/beard/node_modules/mongodb/lib/mongodb/db.js:495:44)
at exports.addServer (/home/ryan/source/node/beard/routes/servers.js:47:6)
at callbacks (/home/ryan/source/node/beard/node_modules/express/lib/router/index.js:164:37)
at param (/home/ryan/source/node/beard/node_modules/express/lib/router/index.js:138:11)
at pass (/home/ryan/source/node/beard/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/home/ryan/source/node/beard/node_modules/express/lib/router/index.js:173:5)

Is this an issue with my database, or do I need to modify the code to reflect updates to mongo?

Thanks for your help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment