Kodeco Forums

How To Write A Simple Node.js/MongoDB Web Service for an iOS App

Learn how to create a simple Node.js and MongoDB web service for an iOS app in this tutorial.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/2663-how-to-write-a-simple-node-js-mongodb-web-service-for-an-ios-app

If you are having an issue with MongoClient.open(), try this code instead:

var url = ā€˜mongodb://localhost:27017/mongo-serverā€™;
// Use connect method to connect to the server
MongoClient.connect(url, function(error, db) {
if (error) {
console.error(
ā€œUnable to connect to MongoDB. Please make sure mongod is running on %s.ā€,
url);
process.exit(1);
}

console.log(ā€œConnected to MongoDB successfully.ā€);
collectionDriver = new CollectionDriver(db);
});

If you get bodyParser deprecation error, use the following code instead:

// add the following line to the top of your index.js
var bodyParser = require(ā€˜body-parserā€™);

// add this following lines after your app.set
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

Deprecation may occur if you use res.send(status, body). Instead, just replace those statements with res.status(status).send(body) and it will work fine.

Hi. Iā€™ve gotten to the point in this tutorial where you add an item via:

curl -H ā€œContent-Type: application/jsonā€ -X POST -d ā€˜{ā€œtitleā€:ā€œHello Worldā€}ā€™ http://localhost:3000/items

However, when I browse to http://localhost:3000/items Iā€™m not seeing any items still. What is the best way to debug this? Iā€™ve added a console log to the app.post(ā€˜/:collectionā€™, function(req, res) function and the code seems to be executing okay.

Any suggestions? Thanks.

1 Like

I got the same error, also not sure what to do. I noticed if you use marcosoulā€™s code above and opened mongodb in the shell and created a database ā€œmongo-serverā€, then created a collection ā€œitemsā€ and inserted elements into that collection, they would show up, but the save method in the collectionDriver appears to fail. Iā€™m new to this so thatā€™s all I figured out.

Iā€™m seeing the same error here as well. @mkatz, would you be able to take a quick look?

(thanks for the awesome tutorial btw!)

Also getting the same error.
Itā€™s a shame that I just killed an afternoon getting through this tutorial only for this to happen. How can I use this lesson if I have no confidence that it works???
@rwenderlich , can you help?

Hi guys, sorry thatā€™s been frustrating. Pretty much the whole stack: iOS/Swift, Javascript, MongoDB, Node.js have all move on quite a bit since this tutorial was written. Weā€™re coming up with a plan on how and when to update this tutorial.

Thanks @mkatz.
FWIW I just noticed this error from when I entered the ā€˜curlā€™ command in terminal

Could not load page: /items/_id

I also had the same error but I changed my package to ā€œmongodbā€:ā€œ1.4.9ā€, npm update and It works for me now

2 Likes

Hi Michael,
Any developments on this?
Thanks.

If you have any issue with ā€œError! Exitingā€¦ Must start MongoDB firstā€
That means you didnā€™t start mongodb yet, use command ā€œcd /usr/local/opt/mongodb/; mongodā€ to start mongodb.
If youā€™ve already start mongodb but it still appear that error,
Fix error with this link:
https://www.demainilpleut.fr/dealing-with-the-mongodb-error-datadb-not-found-in-osx/

The reason is that you forgot to add some code from ā€œUpdating and Deleting Dataā€ part.

If your delete not only delete id, but also cause end connection of port 3000.
Donā€™t use ā€œres.status(status).send(body)ā€ as express recommend.
Use ā€œres.sendStatus(status, body)ā€ instead.

Hi guys, Iā€™m at the end of the ā€œUsing Your Collection Driverā€ section, and when I run index.js I get:
ā€œjs-bson: Failed to load c++ bson extension, using pure JS version
Express server listening on port 3000
Error! Exitingā€¦ Must start MongoDB firstā€

Iā€™ve definitely got mongod running, hereā€™s the output from that:
ā€œ2016-08-16T15:41:06.311-0400 I CONTROL [initandlisten] MongoDB starting : pid=79197 port=27017 dbpath=/data/db 64-bit host=jeff-dewitte-mbp
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] db version v3.2.8
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] git version: ed70e33130c977bda0024c125b56d159573dbaf0
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.2h 3 May 2016
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] allocator: system
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] modules: none
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] build environment:
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] distarch: x86_64
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] target_arch: x86_64
2016-08-16T15:41:06.312-0400 I CONTROL [initandlisten] options: {}
2016-08-16T15:41:06.313-0400 I - [initandlisten] Detected data files in /data/db created by the ā€˜wiredTigerā€™ storage engine, so setting the active storage engine to ā€˜wiredTigerā€™.
2016-08-16T15:41:06.313-0400 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=9G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2016-08-16T15:41:06.826-0400 I NETWORK [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2016-08-16T15:41:06.826-0400 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory ā€˜/data/db/diagnostic.dataā€™
2016-08-16T15:41:06.828-0400 I NETWORK [initandlisten] waiting for connections on port 27017ā€

Iā€™ve tried changing the mongodb version in my package.json file to 3.2.8 to match the output from mongod (since this tutorial is a little old), and then I tried 1.4.9 since that helped someone earlier, but no dice. Anyone know what could be going on?

From btdtphx: ā€œI changed my package to ā€œmongodbā€:ā€œ1.4.9ā€, npm update and It worksā€

I can confirm this fixed the problem for me as well on OSX. Basic steps:

  1. stop node.js if running.
  2. In package.son, change the mongo dependency to: ā€œmongodbā€: ā€œ1.4.9ā€
  3. run npm update
  4. In a separate terminal, start node.js (ā€œnode .ā€ or ā€œnode index.jsā€)
  5. Back in your first terminal, send the post request: curl -H ā€œContent-Type: application/jsonā€ -X POST -d ā€˜{ā€œtitleā€: ā€œHello Worldā€}ā€™ http://localhost:300/items
  6. Go to ā€œhttp://localhost:3000/itemsā€ and see the table is now created.

Additional: the older dependency ā€œmongodbā€: ā€œ1.3.23ā€ does not appear to be compatible with the current mongod daemon. The problem was not with the get, but with the post, which I found by reverting back to 1.3.23 and loading the page from step 6 above and seeing the table with my prior entries. I posted a new entry with step 5 above under the old 1.3.23, then upgraded once again to 1.4.9, restarted node.js and the browser and viola, the new entry appeared in the table.

This is not your problem: ā€œFailed to load c++ bson extension, using pure JS versionā€. Basically mongoDB requires BSON 0.2.12, which on OSX has nothing in its build/release directory. The error is produced by ā€œnode_modules/bson/ext/index.jsā€. There you can see the reason is that index.js canā€™t find the ā€œbsonā€ file/directory in its build/release subfolder. You can get the error to go away by simply copying lib/bson/bson.js (or browser_build/bson.js) into /build/release. Itā€™s a hokey fix. And itā€™s not even necessary, as youā€™ll see in index.js, the very next action taken is to load up the bson.js file from lib/bson/bson.js

As to your error, when you installed mongodb, the author ā€œmkatzā€ told you to note (copy) the summary that was spit out by ā€œbrew install mongodbā€. In my case, I got a message in terminal saying ā€œOr, if you donā€™t want/need a background service you can just run:
mongod --config /usr/local/etc/mongod.confā€. Starting the mongod daemon with this line works for me. To note: trying to start it by just calling ā€œmongodā€ produces an error similar to yours. Remember if youā€™re changing your package.json file to depend on mongo 1.4.9, youā€™ll need to run ā€œnpm updateā€ to actually install it to you project folder.

In collectionDriver.js, calling ā€œremoveā€ does not return the removed document. It returns the number of documents removed. This is probably remove() was altered when I updated mongo from 1.3.23 to 1.4.9 in package.json. In order to return the removed object, you must ā€œgetā€ it from the DB prior to the delete, then return it in the callback in place of ā€œdocā€.

Iā€™ve rewritten CollectionDriver.prototype.delete as follows:

CollectionDriver.prototype.delete = function(collectionName, entityId, callback) {
var self = this;
this.getCollection(collectionName, function(error, the_collection) { //A
if (error) callback(error);
else {
self.get(collectionName, entityId, function(error, objs){
var objectToDelete = objs;
if (error) callback(error);
else {
the_collection.remove({ā€˜_idā€™:ObjectID(entityId)}, function(error,doc) { //B
var doc_string = "DOCS REMOVED: " + doc;
console.log(doc_string); //sent to SERVER CONSOLE
if (error) callback(error);
else callback(null, objectToDelete);
});
}
});
}
});
};

thx, it solved mine too