用Mongoose填充其他集合中的记录数 [英] Populating count of records from other collection with Mongoose

查看:56
本文介绍了用Mongoose填充其他集合中的记录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2种猫鼬模型,分别是Book和Users.我想这样做:当找到一本书时,我想获取当前书籍用户的数量.

I have 2 Mongoose models, Book and Users. i want to do that: When find a book, i want to get the count of current 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;
        }
);

现在此代码可以读取一本书,但是我想在Users模型中填充用户数量,并将其添加到新的读取对象中.

right now tis code fetch a book, but i want to populate count of users inside Users model and add them to the new fetched book object.

我阅读了这份文件,但我做不到: 人口

i read this document but i can't accomplish that: 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字段的长度即可.

You'll need to update both schema when you add people to books or books to people. To get the current book users, just find the book and then get length of it's owner_ids field.

这篇关于用Mongoose填充其他集合中的记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆