Filling the number of records from another collection using Mongoose

I have 2 models Mongoose, Book and Users. I want to do this: when you find a book, I want to get the number of users of the current book.

this is a book model:

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;

this is user model:

var mongoose = require('mongoose');
var Book = require('../book');
var schema = new mongoose.Schema({
    user_name: String,
    book_id: String
});
var users = mongoose.model('users', schema);
module.exports = users;

I'll take a book like this:

Book.find({book_name:name).exec(
        function(err, book) {
            if (err) {
                throw err;
            }
            var new_book = book;
        }
);

this code is retrieving the book right now, but I want to populate the number of users inside the user model and add them to the new selected book object.

I am reading this document, but I cannot do it: Population

+4
source share
2 answers
User = new mongoose.Schema({
 //existing user properties
 owned_books: [{type: mongoose.Schema.Types.ObjectId, ref: 'book'}]
}}
var users = mongoose.model('users', User);

var schema = new mongoose.Schema({
  book_name: String,
  book_publisher: String,
  owner_ids: [{type: mongoose.Schema.Types.ObjectId, ref: 'users'}]
});
var book = mongoose.model('book', schema);

, . , , owner_ids.

0

, , . , - . , , : reverse-populate.

0

Source: https://habr.com/ru/post/1599266/


All Articles