Mongoose error: Schema hasn't been registered for model when populate

This is all I had to do Customer.findOne({}).populate({ path: 'created_by', model: User }) instead of this Category.findOne({}).populate({'author'})


IF YOU (really) USE MULTIPLE mongoDB CONNECTIONS


I do realise that this is not the case for the OP, but if you genuinely use multiple connections you MUST provide the model when using .populate(), as mongoose will only "find" models on the same connection. ie where:

var db1 = mongoose.createConnection('mongodb://localhost:27017/gh3639');
var db2 = mongoose.createConnection('mongodb://localhost:27017/gh3639_2');
var userSchema = mongoose.Schema({
  "name": String,
  "email": String
});

var customerSchema = mongoose.Schema({
  "name" : { type: String },
  "email" : [ String ],
  "created_by" : { type: mongoose.Schema.Types.ObjectId, ref: 'users' },
});

var User = db1.model('users', userSchema);
var Customer = db2.model('customers', customerSchema);

Correct:

Customer.findOne({}).populate('created_by', 'name email', User)

or

Customer.findOne({}).populate({ path: 'created_by', model: User })

Incorrect (produces "schema hasn't been registered for model" error):

Customer.findOne({}).populate('created_by');

The problem is that you are creating a new connection in each and every model, so you end up with a bunch of different connection objects. Even though they are pointing to the same database, mongoose models don't know about other connections. You should instead create the connection object in your main app and then pass it around.

server.js

var express = require('express');
var mongoose = require('mongoose');

var app = express();
var conn_new_app = mongoose.createConnection('mongodb://localhost/new_app');
var Feed_Post = require('./app/models/feed_post.model')(conn_new_app);

app.get('/testget', function(req,res){
  Feed_Post.findOne().populate('user_id').exec(function(err, c) {
    if (err) { return console.log(err); }
    console.log(c.fk_user.userName);
  });
});

Then modify your models so they are actually a function:

feed_post.model.js

module.exports = function (connection) {
  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;

  var feed_postSchema = new Schema({
    user_id:  { type: Schema.Types.ObjectId, ref: 'User_Fb' },
    content: String,
    location: String,
    image: [{ type : String }]
  });

  return connection.model('Feed_Post', feed_postSchema);;
}

Also, like Adrian mentions, you can use mongoose as a singleton. However, I do recommend using createConnection as you did because if you ever need a second connection, you won't have to refactor the connection code to your first database.