How the mongoose population works

advertisements

I want to use Mongoose Population and fetch some information from other collections. My models are:

var mongoose = require('mongoose');
var Users = require('../users');
var schema = new mongoose.Schema({
    book_name: String,
    book_publisher: String
});
var book = mongoose.model('book', schema);
module.exports = book;

And

var mongoose = require('mongoose');
var Book = require('../book');
var Schema = mongoose.Schema;
var schema = new mongoose.Schema({
    user_name: String,
    books: [{ type: Schema.Types.ObjectId, ref: 'Book' }]
});
var users = mongoose.model('users', schema);
module.exports = users;

I want to store each user books inside books field and populate them from Books collection. But i cant understand, How this connection happens? How my Users schema connects to Book schema? I mean, _id field inside book schema should be the same with _id in users schema? i didn't specify any relation i think but in every tutorial i read, all of them are like this. I want populate each user books separately but what is the key item for comparing in two collection? have i do something in find method? this is my find:

Users.find({book_name:name).populate('books').exec(
        function(err, users) {
            if (err) {
                throw err;
            }
            var new_user = users;
        }
);

in fact my question is, how that .populate('books') works. I never say which field in books schema related to users schema. i'm confused.

And right now when i run this, I get nothing in populated field, it's empty. should i write a save method and saved items must be under this relation? in my App, this two collection filled separately and from separate sources.


The populate function works like this, you specify in the schema that the field(in this case books) is an ObjectId and it's ref is the model 'Book', when you populate, mongoose goes to the Book collection and searches for the model with the Id of the book you specified in User, so he converts the field do a Book field instead of the ObjectId.

To see why your code does not work i need to know how you're creating the objects aswell, but with a quick glance i think this may be causing because you specify the model name as 'book' and used in the ref 'Book', i believe mongoose is case-sensitive.