Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Populate in Node JS

I've been trying to follow the information in Mongoose Population, but I'm getting the exception:

MissingSchemaError: Schema hasn't been registered for model "undefined".

The code I have goes like this:

mongoose = require('mongoose');
Schema = mongoose.Schema;
mongoose.connect(MONGO_SERVER);
ObjectId = Schema.ObjectId;

var FirstSchema = new Schema({
    label       : String
});
var SecondSchema = new Schema({
    first_id           : [{ type: mongoose.Schema.ObjectId, ref: 'First' }],
    type           : String,
    ...
});
var first= mongoose.model('First', FirstSchema);
var second= mongoose.model('Second', SecondSchema);

function test() {
    ...
    second.find({}).populate('first_id').exec(function(err,data){return true;});
    ...
}

And the error occurs on the populate, I've tweaked it a number of times to different answers found on forums, and I'm sure it will be something simple, but can someone point me in the right direction?

Cheers.

like image 841
Jester Avatar asked Feb 19 '13 04:02

Jester


1 Answers

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.

like image 117
Jone Polvora Avatar answered Sep 19 '22 17:09

Jone Polvora