Fcoder Fcoder - 5 months ago 20
Javascript Question

fetching data from other collections inside Mongoose find method

I'm working on a App with Node.js and mongoose(mongodb). Is there any way to fetch information from other collections inside find method except

model population
?
population
works with
_id
and my id's in the other collection cant be duplicate and i cant have one to many relation.

For example every user has more than one books. in the books schema
_id
's should be duplicate and a bunch of them has the same user id. But i don't want this. i want to compare other field.

I read
document#population
in Mongoose documentation but i can't understand:
http://mongoosejs.com/docs/api.html#document_Document-populate

i can't believe for this simple need, Mongoose doesn't have a good api.

this is my schema's:

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;

Answer

Essentially, the problem is not with mongoose but mongo. What you're trying to do is basically pull relational data in a non-relational database. From experience I suggest not doing this. If you can't avoid it, use postgres. Postgres supports json data.

In mongoose you can load first level relations (users -> posts) using the .populate method. If you want to pull in a second level relation (users -> posts -> replies), then you end up needing to manually create joins in code. So if a user has multiple books, you can setup your schemas like this.

   User = new mongoose.Schema({
     //existing user properties
     owned_books: [{type: mongoose.Schema.Types.ObjectId, ref: 'book'}]
   }}

    //now you can query users and populate their books by doing
    Users.find().populate('owned_books').exec(callback)

Edit: It could go the other way around, where the book has a collection of users. In any case, _id needs to be unique in a table, but as a field of another document it does not need to be unique, unless you've put an index on that field.