当前位置 : 主页 > 网页制作 > Nodejs >

node.js – 使用Mongoose填充其他集合中的记录数

来源:互联网 收集:自由互联 发布时间:2021-06-16
我有2个Mongoose模型,Book和Users.我想这样做:当找到一本书时,我想得到当前图书用户的数量. 这是书模型: var mongoose = require('mongoose');var Users = require('../users');var schema = new mongoose.Schema({
我有2个Mongoose模型,Book和Users.我想这样做:当找到一本书时,我想得到当前图书用户的数量.

这是书模型:

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;

这是用户模型:

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;

我拿这样的书:

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

现在tis代码获取一本书,但我想填充用户模型中的用户数,并将它们添加到新获取的书对象.

我读了这篇文章,但我无法做到这一点:
Population

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字段的长度.

网友评论