Common MongoDB and Mongoose Pitfalls
And their solutions
MongoDB and Mongoose are commonly used with Node JS projects. In this article, you’ll find a small list of pitfalls that can be easily avoided and save you hours of debugging time.
If you are new to Mongo and Mongoose, I highly recommend the Mongoose quick start guide:
Everything in this article will be loosely based on the examples given in the quick start guide.
Pitfall #1: Overthinking the guide
When reading the quick start guide, adding a kitten named ‘Silence’ feels like creating a new collection instead of inserting a document into the kitten collection.
So this:
var silence = new Kitten({ name: 'Silence' });
creates a new document, not a new collection.
Pitfall #2: Remember to save
It’s easy to do this:
var fluffy = new Kitten({ name: 'fluffy' });
But forget about doing this:
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
fluffy.speak();
});
If you ever have trouble finding your version of fluffy in the collection, check if you have saved it first.
Pitfall #3: MongoDB connection error when starting a new project
When this problem occurs, there is a high possibility that you still have mongod running for your previous project which is creating a conflict.
The error message may look something like this:
npm ERR! code ELIFECYCLE
npm ERR! errno 48
npm ERR! <file location> db-start: `mongod --dbpath ./database/data/db`
npm ERR! Exit status 48
npm ERR!
npm ERR! Failed at the <file location> db-start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Go to your project folder in the terminal and type this:
(press enter after each line)
mongouse admindb.shutdownServer()
Pitfall #4: db.collection.find()
The ‘.find()’ returns every line in the specified collection. Here’s an example:
- You have a db called ‘test’
- Inside ‘test’, you have a collection called ‘items’
If you want all the data inside items, type this into terminal:
(press enter after each line)
mongouse testdb.items.find()
and these do not work:
test.items.find()items.find()
Other useful tips
When testing: use db.dropDatabase() to delete the entire database after testing connections, schemas, or after you finished testing.
Creating a database: after you have defined a new schema and model, a new database is automatically created after you insert the first document into the schema. Don’t waste your time looking for how to create a new database.
Other helpful resources: The official Mongoose Docs and MongoDB docs are quite handy in solving most of the problems that you might have.