Object modeling with Mongoose

Mongoose is an object data modeling library (ODM) that allows you to define schemas for your data collections. You can find out more about Mongoose on the project website: http://mongoosejs.com/.

To connect to a MongoDB instance using the mongoose variable, we first need to install npm and save Mongoose. The save flag automatically adds the module to your package.json with the latest version, thus, it is always recommended to install your modules with the save flag. For modules that you only need locally (for example, Mocha), you can use the savedev flag.

For this project, we create a new file db.js under /src/lib/db.js, which requires Mongoose. The local connection to the mongodb database is made in mongoose.connect as follows:

var mongoose = require('mongoose'),
module.exports = function(app)
{ 
  mongoose.connect('mongodb://localhost/movies', {
  mongoose: { safe: true
}
}, function(err) { if (err) 
{
  return console.log('Mongoose - connection error:', err);
}
});
return mongoose; 
};

In our movies database, we need separate schemas for actors and movies. As an example, we will go through object modeling in our actor database /src/models/actor.js by creating an actor schema as follows:

// /src/models/actor.js
var mongoose = require('mongoose'),
var generateId = require('./plugins/generateId'),

var actorSchema = new mongoose.Schema({ 
  id: {
    type: Number, 
    required: true, 
    index: {
      unique: true
    }
  },
  name: {
    type: String, 
    required: true
  }, 
  birth_year: {
    type: Number, 
    required: true

  }, 
  movies: [{
    type : mongoose.Schema.ObjectId,
    ref : 'Movie'
  }]
});
actorSchema.plugin(generateId());
module.exports = mongoose.model('Actor', actorSchema);

Each actor has a unique id, a name, and a birth year. The entries also contain validators such as the type and boolean value that are required. The model is exported upon definition (module.exports), so that we can reuse it directly in the app.

Alternatively, you could fetch each model through Mongoose using mongoose.model('Actor', actorSchema), but this would feel less explicitly coupled compared to our approach of directly requiring it.

Similarly, we need a movie schema as well. We define the movie schema as follows:

// /src/models/movies.js
var movieSchema = new mongoose.Schema({ 
  id: {
    type: Number, 
    required: true, 
    index: {
      unique: true
    }
  }, 
  title: {
    type: String, 
    required: true
   }, 
   year: {
     type: Number, 
     required: true
   }, 
   actors: [{
     type : mongoose.Schema.ObjectId, 
     ref : 'Actor'
   }]
});

movieSchema.plugin(generateId());
module.exports = mongoose.model('Movie', movieSchema);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.34.161