Search code examples
mongodbmongoosemongoose-schemamongoose-populate

Mongoose Schema hasn't been registered for model when populating


I am trying to join 2 collections using the populate method, I have 3 models artists, albums and songs. My mongodb connection is made on server.js. my artist model is :

var mongoose = require('mongoose');
//var Album = mongoose.model('Album').schema;
console.log(Album);
var artistsSchema = mongoose.Schema({
  name:{
    type:String,
    required:true
  },
  albums:{
    type:[{type:mongoose.Schema.Types.ObjectId,ref :'Album'}]
  }

});
var Artist =  mongoose.model('Artist',artistsSchema);
module.exports.getArtistsFull = function(callback,limit)
{
  Artist.find().limit(1)
      .populate({
      path:'albums'
      ,populate :{path:'albums'}
    }).exec(callback);
}

And my albums model:

var mongoose = require('mongoose');
var albumsSchema = mongoose.Schema({
  name:{
    type:String,
    required:true
  },
  songs:{
    type:[{type:mongoose.Schema.Types.ObjectId,ref :'Song'}]
  }
});
var Album = mongoose.model('Albums',albumsSchema);
module.exports.getAlbumsWithSongs = function(id,callback,limit){
  Album.findById(id)
      .populate({
      path : 'songs',
      populate :{path:'songs'}
    }).exec(callback);
}

Whenever I call Artist.getArtistsFull function I get an error"Schema hasn't been registered for model Album", I used console.log(Album) on my Album variable inside artist model and I got the functions that were written there, but I don't have access to albumsSchema.


Solution

  • The problem was actually a simple typo

    var Album = mongoose.model('Albums',albumsSchema);
    

    changed to

    var Album = mongoose.model('Album',albumsSchema);