Node.js Academy

Interact with a database 🍃

#ege-academy-nodejs @rbung @yagong

What is it For ?

Get data from a database

Put data into a database

Relationnal or NoSql

#ege-academy-nodejs @rbung @yagong

How ?

#ege-academy-nodejs @rbung @yagong

Other options ?

#ege-academy-nodejs @rbung @yagong

Relational databases (MySQL, PostgreSQL, SQLite) with Knex or Sequelize

#ege-academy-nodejs @rbung @yagong

So why Mongoose ?

#ege-academy-nodejs @rbung @yagong

  • Define schemas
  • Validation
  • Convenient methods
  • Populate

Mongoose

#ege-academy-nodejs @rbung @yagong

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

const Cat = mongoose.model('Cat', { name: String });

const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));

All static methods available by default : https://mongoosejs.com/docs/queries.html

Mongoose - Populate

#ege-academy-nodejs @rbung @yagong

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

Story.
  findOne({ title: 'Casino Royale' }).
  populate('author').
  exec(function (err, story) {
    if (err) return handleError(err);
    console.log('The author is %s', story.author.name);
    // prints "The author is Ian Fleming"
  });

How to test ?

#ege-academy-nodejs @rbung @yagong

#ege-academy-nodejs @rbung @yagong

Made with Slides.com