Working with models in mongoose
In this post I will be giving a quick overview of working with models in mongoose.js. If you are not aware mongoose.js is a javaScript library to help make it easier to work with mongodb, a popular javaScript friendly database solution that is used in node.js powered full stack apps.
1 - what to know
This is not a getting started post on node.js, or mongodb both of which are required to get anything out of this post. As of this writing I have written a getting started post on mongodb, but will not get into detail about everything in this post, just working with models with mongoose.
2 - setup
For this project I will of course need node.js, and mongodb installed, and I assume that the mongodb server is up and running on the default port. If not some values in the project should be changed.
3 - An example of a Model in mongoose.
For an example of using mongoose to create an instance of a Model I made a project in which I created a User Model that represents a user in a client database. I made additional scripts for interacting with that model, as well as connecting to mongodb, an droping the database.
3.1 - The users.js file that will contain the Model
So the most Important file in the project is the users.js file that will contain
|
|
3.2 - The connect.js file
For this demo I started to break everything down into separate files for certain tasks such as listing all the instances of a model, or connecting to mongodb in the first place. So for this demo I made a connect.js file that actually connects to mongodb, and then returns a promise that will resolve if the connection works. It also returns mongoose as the first argument, so I do not need to require it again in a script that makes use of this.
|
|
3.3 - The create.js file.
This file uses the connect.js file to connect to mongodb, and then it also imports the User Model from users.js. Once I have those two things to work with I use it to create a new User.
|
|
So when I call the script from the command line like this.
|
|
If all goes well a new user named Dustin is added to the database, and the instance of User is logged to the console. To confirm that the instance of the User model is in the database, I can use another script that will list the users.
3.4 - The list.js file.
|
|
3.5 - The dropall.js file
This is a quick script that I use to just drop the whole database, and start over. Not a bit deal for a simple demo project like this.
|
|
4 - conclusion
I have not covered everything these is to know about models in this post. However I will be writing a lot more content on mongoose and mongodb in the coming days, and as such I may get around to revising this further as well as link to more relevant posts on mongoose as my collection of content on mongodb grows.