Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted March 16th, 2016
Lets use Mongoose

What is mongoose

Mongoose is a Node.js library that provides MongoDB object mapping with a familiar interface within Node.js. what is Object Relational Mapping (ORM) or, Object Data Mapping (ODM), this means that Mongoose translates data in the database to JavaScript objects for use in your application. Let’s take a look at creating and storing data in a collection using MongoDB and Mongoose.

Connecting to MongoDB?

We are going to make a database connection to the test database. The best part about mongoDB is that when we connect to the database and it does not exist yet it will create it automatically.

// Require mongoose use "npm install mongoose --save" first
var mongoose = require('mongoose');

// Creating the database object
var db = mongoose.connection;

// Adding listeners
db.on('error', console.error);
db.once('open', function() {
  // Create your schema's and models here.
});

// Connecting to database: test on localhost
mongoose.connect('mongodb://localhost/test');

How to make my schema and model

In mongoDB we use schemas to define the structure of data within a collection. When you are used to an SQL you can compare a schema with a table. But there are some big differences. Models are used to create instances of data that will be stored in documents. I will show you an example of how we create a schema and a model.

var userSchema = new mongoose.Schema({
  fristname: { type: String },
  surname: String,
  age: Number,
  isadmin: Boolean
});

var User = mongoose.model('User', userSchema);

As you can see we do not declare an ID in the userSchema but why? Well mongoDB automatically creates an ID for every collection. Notice that the User model is capitalized, this is because the result is a constructor function that is used to create instances of the model.

Create, Retrieve, Update, and Delete (CRUD)

Well its simple what do we want to do with data of course we want to:
– create
– retrieve
– update
– delete

I’m going to explain to you how you can use all those 4 things within mongoose.

Create

var ian = new User({
  fristname: 'Ian',
  surname: 'Gerrebrands',
  age: 23,
  isadmin: true
});

ian.save(function(err, ian) {
  if (err) return console.error(err);
});

Notice how we use the Model’s constructor function we declared earlier to create an instance of a User. We use the save method mongoose provided us with to save this object. mongoose automatically transforms it into data the mongoDB database can read.

Retrieve

We created a User but how can we retrieve this data? We can do this by using the find or findOne methods mongoose provided us with.

User.findOne({ firstname: 'Ian' }, function(err, doc) {
  if (err) return console.error(err);
  // Notice how I console log the doc param.
  // The doc param represents the found data.
  // With the doc param you can also manupilate the data.
  console.log(doc);
});

// Find all users.
User.find(function(err, docs) {
  if (err) return console.error(err);
});

// Find all admins.
User.find({ isadmin: true }, function(err, movies) {
  if (err) return console.error(err);
  console.dir(movies);
});

We can use object to filter search the database for information in the example we only give one attribute but we can give a lot more.

Update and delete

This one is tricky most people including myself expect a delete and update method but there is none. So how can we delete data of update data is the big question now. Well why they did it like this is because we need to find data first before we can manipulate it. So we use the find or findOne method first and then manipulate the data by using the doc/docs param we received from the callback function like this.

User.findOne({ firstname: 'Ian' }, function(err, doc) {
  if (err) return console.error(err);
  // For updating the found document
  doc.age = 24;
  doc.save(function (err) {
    return console.error(err);
  });
});

User.findOne({ firstname: 'Ian' }, function(err, doc) {
  if (err) return console.error(err);
  // For removing the found document
  doc.remove();
});

Notice how we can update the attribute of an object and then save it to the database to update it. This makes it very easy to update things inside your database. That’s why I like mongoose so much you do not have to learn a whole new query language its just a library you need to learn.

Posted by Ian Gerrebrands

Leave a Reply

Your email address will not be published. Required fields are marked *