Mongoose Populate in Node JS
In your schema definitions, I see that you have defined 'first_id' as an array in Second schema. Compared to a relational database, this will be like an one-to-many relationship in which the parent table is the Second collection, and First collection as the child. Then you're doing wrong trying to populate the second with the first.
Suppose I have a Users collection, and a Clients collection, in which each client has an user related to it. Then the code will be:
var mongoose = require('mongoose');mongoose.connect('mongodb://userName:password@server:port/dbname');var conn = mongoose.connection;conn.on('error', console.error.bind(console, 'connection error:'));conn.once('open', function callback () { console.log('connected ');});var user = mongoose.Schema({ userName: String});var client = mongoose.Schema({ fk_user: { type: mongoose.Schema.ObjectId, ref: 'Users' }, name: String});var UserModel = mongoose.model('Users', user);var ClientModel = mongoose.model('Clients', client);ClientModel.findOne().populate('fk_user').exec(function(err, c) { if (err) { return console.log(err); } console.log(c.fk_user.userName);});
Hope this give you some point to help.
i had the same error
Schema hasn't been registered for model "States".
sometimes it might also be that the model you are trying to reference is not assigned to a schema .
like in the code below
first : i was trying to reference the 'states' model i created with States but it was not the name of the model instead the name was states
var CountriesSchema = new Schema({name:{ type:String,required:true},capital:{type:String},description:{type:String},cord:{ latitude:{type:Number}, longitude:{type:Number}},state:[{type:Schema.Types.ObjectId , ref:'States'}],date_created:{type:Date},date_modeified:{type:Date}});
Meanwhile the real name of the model was states
var State = mongoose.model('states',StateSchema) ;module.exports = State ;
All i did was change the States to states
var CountriesSchema = new Schema({ name:{ type:String,required:true}, capital:{type:String}, description:{type:String}, cord:{ latitude:{type:Number}, longitude:{type:Number} }, state:[{type:Schema.Types.ObjectId , ref:'states'}], date_created:{type:Date}, date_modeified:{type:Date}});