This tutorial is out of date and no longer maintained.
Node.js and MongoDB are a pair made for each other. Being able to use JSON across the board and JavaScript makes development very easy. This is why you get popular stacks like the MEAN stack that uses Node, Express (a Node.js framework), MongoDB, and AngularJS.
CRUD is something that is necessary for almost every application out there. We have to create, read, update, and delete information all the time.
Today we’ll be looking at code samples to handle CRUD operations in a Node.js, ExpressJS, and MongoDB application. We’ll use the popular Node package, mongoose.
These code samples were used to create a Node.js RESTful API since you are performing CRUD functions when creating an API. Read through that tutorial to see these commands in action. This article will be more of a reference for the various commands and their usage.
mongoose is an object modeling package for Node that essentially works like an ORM that you would see in other languages (like Eloquent for Laravel).
Mongoose allows us to have access to the MongoDB commands for CRUD simply and easily. To use mongoose, make sure that you add it to your Node project by using the following command:
- npm install mongoose --save
Now that we have the package, we just have to grab it in our project:
- var mongoose = require('mongoose');
We also have to connect to a MongoDB database (either local or hosted):
- mongoose.connect('mongodb://localhost/myappdatabase');
Let’s get to the commands.
Before we can handle CRUD operations, we will need a mongoose Model. These models are constructors that we define. They represent documents that can be saved and retrieved from our database.
Mongoose Schema The mongoose Schema is what is used to define attributes for our documents.
Mongoose Methods Methods can also be defined on a mongoose schema. These are methods
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean,
location: String,
meta: {
age: Number,
website: String
},
created_at: Date,
updated_at: Date
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
This is how a Schema is defined. We must grab mongoose
and mongoose.Schema
. Then we can define our attributes on our userSchema
for all the things we need for our user profiles. Also, notice how we can define nested objects as in the meta
attribute.
The allowed SchemaTypes
are:
We will then create the mongoose Model by calling mongoose.model
. We can also do more with this like creating specific methods. This is a good place to create a method to hash a password.
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema ...
// custom method to add string to end of name
// you can create more important methods like name validations or formatting
// you can also do queries and find similar users
userSchema.methods.greet = function() {
// add some stuff to the users name
this.name = 'Hello ' + this.name;
return this.name;
};
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
Now we have a custom model and method that we can call in our code:
// if our user.js file is at app/models/user.js
var User = require('./app/models/user');
// create a new user called chris
var chris = new User({
name: 'Chris',
username: 'chris',
password: 'password'
});
// call the custom method.
// this will greet the user.
chris.greet(function(err, name) {
if (err) throw err;
console.log(name);
});
// call the built-in save method to save to the database
chris.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
});
This is a very useless custom method, but the idea for how to create a custom method and use it stands. We can use this for making sure that passwords are hashed before saving, having a method to compare passwords, find users with similar attributes, and more.
We also want to have a created_at
variable to know when the record was created. We can use the Schema pre
method to have operations happen before an object is saved.
Here is the code to add to our Schema to have the date added to created_at
if this is the first save, and to updated_at
on every save:
// on every save, add the date
userSchema.pre('save', function(next) {
// get the current date
var currentDate = new Date();
// change the updated_at field to current date
this.updated_at = currentDate;
// if created_at doesn't exist, add to that field
if (!this.created_at)
this.created_at = currentDate;
next();
});
Now on every save, we will add our dates. This is also a great place to hash passwords to be sure that we never save plaintext passwords.
We can also define more things on our models and schemas like statics and indexes. Be sure to take a look at the mongoose docs for more information.
We’ll be using the User
method we created earlier. The built-in save
method on mongoose Models is what is used to create a user:
// grab the user model
var User = require('./app/models/user');
// create a new user
var newUser = User({
name: 'Test',
username: 'test',
password: 'password',
admin: true
});
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
There are many reasons for us to query our database of users. We’ll need one specific user, all users, similar users, and many more scenarios. Here are a few examples:
// get all the users
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
console.log(users);
});
// get the user test
User.find({ username: 'test' }, function(err, user) {
if (err) throw err;
// object of the user
console.log(user);
});
// get a user with ID of 1
User.findById(1, function(err, user) {
if (err) throw err;
// show the one user
console.log(user);
});
You can also use MongoDB query syntax.
// get any admin that was created in the past month
// get the date 1 month ago
var monthAgo = new Date();
monthAgo.setMonth(monthAgo.getMonth() - 1);
User.find({ admin: true }).where('created_at').gt(monthAgo).exec(function(err, users) {
if (err) throw err;
// show the admins in the past month
console.log(users);
});
Here we will find a specific user, change some attributes, and then re-save them.
// get a user with ID of 1
User.findById(1, function(err, user) {
if (err) throw err;
// change the users location
user.location = 'uk';
// save the user
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
Remember that since we created the function to change the updated_at
date, this will also happen on save
.
An even easier method to use since we don’t have to grab the user, modify, and then save. We are just issuing a MongoDB findAndModify
command.
// find the user test
// update them to test2
User.findOneAndUpdate({ username: 'test' }, { username: 'test2' }, function(err, user) {
if (err) throw err;
// we have the updated user returned to us
console.log(user);
});
### Find By ID and Update
```javascript
// find the user with id 4
// update username to test4
User.findByIdAndUpdate(4, { username: 'test4' }, function(err, user) {
if (err) throw err;
// we have the updated user returned to us
console.log(user);
});
// get the user test
User.find({ username: 'test' }, function(err, user) {
if (err) throw err;
// delete the user
user.remove(function(err) {
if (err) throw err;
console.log('User successfully deleted!');
});
});
// find the user with username test
User.findOneAndRemove({ username: 'test' }, function(err) {
if (err) throw err;
// we have deleted the user
console.log('User deleted!');
});
// find the user with id 4
User.findByIdAndRemove(4, function(err) {
if (err) throw err;
// we have deleted the user
console.log('User deleted!');
});
Hopefully, this will act as a good reference guide when using the mongoose package in Node.js and MongoDB applications.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!