Mongoose Find All然后在其他模式中查找所有模式

时间:2017-10-20 19:02:53

标签: javascript node.js mongodb mongoose

在我的应用程序中,我需要找到类别,然后我想要这个类别的书籍

const CategorySchema = mongoose.Schema({
    displayname: String,
    category: String
});

module.exports = mongoose.model('Category', CategorySchema);

}

const BookSchema = mongoose.Schema({
    name: String,
    img: String,
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
    }
});

module.exports = mongoose.model('Books', BookSchema);

我需要这样的回复

categories = [
 {
  category: 'News',
  books: [{name:'',id''},{}..]
 },
 {
  category: 'Sports',
  books: [{name:'',id''},{}..]
 }
];

所以我的代码看起来像这样

Router.get('/categories/', (req, res) => {
    Category.find({}, (err, categories) => {
        Promise.all(categories.map(category => {
            return Book.find({category: category._id}).then( books => {
                return {
                    category: category,
                    books: books
                };
            })
        })).then( categories => {
            res.json(categories);
        })
    })
});

请有人知道这个查询是否有更好的解决方案? 谢谢大家!

2 个答案:

答案 0 :(得分:2)

这个怎么样?

Router.get('/categories/', (req, res) => {
  Book.find().populate('category').then( books => {
    var categories = {}
    for(var i = 0; i <  books.length; i++){
      categories[books[i].category.displayname] = {
        category: books[i].category.displayname
        books: categories[books[i].category.displayname].books ? categories[books[i].category.displayname].books.push(books[i]) : [books[i]]
      };
    }
    var result = [];
    for(var key in categories){
      result.push(categories[key])
    }
    return result;
  });
});

它可能更漂亮,但它只向您的数据库发出一个请求,并且应该按照您想要的方式工作

答案 1 :(得分:0)

来自http://mongoosejs.com/docs/populate.html

Book.
  find({}).
  populate('category').
  exec(function (err, story) {
    if (err) return handleError(err);
    // Do other things
  });