0

I would like to combine different documents and retrieve them from a mongodb database using Promises.

So I have the author_id of a author and would like to display all the books the author has and in which library they are stored and if they are available or not. This in a axpress server using pug to render the page.

I first lookup the author, then I want to go through the libraries and search all the available books end if the author of the book is the same author we search I want to display if it was found in what library it was found and if it was found in the available or unavailable list.

   var AuthorSchema = new Schema(
    {
        first_name: {type: String, required: true, max: 100},
        family_name: {type: String, required: true, max: 100},
        date_of_birth: {type: Date},
        date_of_death: {type: Date},
    });

    var BookSchema = new Schema(
    {
        title: {type: String, required: true},
        author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
        summary: {type: String, required: true},
        isbn: {type: String, required: true},
        genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
    });
    var library = new Schema({

        name:{type:String,required:true},
        available_books:[{type:Schema.Types.ObjectId,ref:'Book'}],
        unavailable_books:[{type:Schema.Types.ObjectId,ref:'Book'}]
    });

//this is the code I came up with,
new Promise((resolve,reject)=>{
  author.findById(id).exec(function(err,author){
  if(err) reject(err)
  else resolve(user)

  }
})
.then(author => {
// stuck here, probs search all the library their available books eend for each book check if the author is the same. 




}

How would I map the books with the library name they are in and if they are available or not, (so 3 colums next to eachoher) with the book name, library name and if they are available or not.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
swaffelay
  • 323
  • 2
  • 10

1 Answers1

1

There are two main approaches to this problem:

  1. Use the aggregation framework's $lookup to have mongo combine those collections into a single result for you: How to join multiple collections with $lookup in mongodb
  2. Use app-side code to combine the collections (this is pseduocode):
const books = await Books.find(authorId);
const bookObjectIds = books.map(({_id}) => _id);
const libraries = await Library.find({$or: [
  {available_books: {$in: bookObjectIds} },
  {unavailable_books: {$in: bookObjectIds} },
]});
...combine books & libraries into your desired format
klhr
  • 3,300
  • 1
  • 11
  • 25