Guest User

Query Chaining

a guest
Jan 30th, 2018
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ========== THIS IS MY AUTHOR SCHEMA ============
  2. authorSchema = new mongoose.Schema({
  3.     name: {
  4.         type: String,
  5.         required: true
  6.     },
  7.     books: [{
  8.         type: mongoose.Schema.Types.ObjectId,
  9.         ref: 'Book'
  10.     }],
  11. });
  12.  
  13. // ========= THIS IS MY BOOK SCHEMA =========
  14. const bookSchema = new mongoose.Schema({
  15.     title: {
  16.         required: true,
  17.         type: String
  18.     },
  19.     authors: [{
  20.         id: {
  21.             type: mongoose.Schema.Types.ObjectId,
  22.             ref: 'Author'
  23.         },
  24.         name: String
  25.     }],
  26.     identifiers: [],
  27.     publisher: String,
  28.     publishedDate: Date,
  29.     description: String,
  30.     textSnippet: String,
  31.     imageURL: String,
  32.     categories: [],
  33. });
  34.  
  35. // ====== THIS IS HOW I CURRENTLY GET ALL THE BOOKS (THIS IS WHERE I WANT TO FILTER THE RESULT TO MATCH OTHER SEARCHES) ==========
  36.  
  37. db.Author.find({'name': authorSearch})
  38.                 .populate('books')
  39.                 .limit(limit)
  40.                 .skip(limit * page)
  41.                 .then(function(authors){
  42.                     if(authors.length > 0){
  43.                         const books = [];
  44.                         authors.forEach(function(author){
  45.                             books.push(...author.books);
  46.                         });
  47.                         return books;
  48.                     }
  49.                 });
Advertisement
Add Comment
Please, Sign In to add comment