简体   繁体   中英

Mongoose Find All then find all in other schema for each

in my application i need to find Categories, then i want Books for this Categories

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);

i need a response like this

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

so my code looks like this

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);
        })
    })
});

please some one know if have better solution for this query? thanks all!

How about this?

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;
  });
});

It could be prettier, but it only makes one request to your db and should work the way you want

From http://mongoosejs.com/docs/populate.html

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

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