简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM