在mongodb中合并不同的文档

时间:2019-03-07 17:26:27

标签: javascript node.js mongodb mongoose

我想合并不同的文档,并使用Promises从mongodb数据库中检索它们。

因此,我具有作者的author_id,并希望显示该作者拥有的所有书籍以及它们存储在哪个库中以及是否可用。在使用pug渲染页面的axpress服务器中。

我首先查找作者,然后我想浏览所有图书馆,如果书的作者与我们搜索的作者相同,那么我想查找所有可用的书,如果在找到的书库中找到该书,我想显示该作者以及是否在可用或不可用列表中找到它。

   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. 




}

我该如何映射书籍所在的图书馆名称以及是否可以使用(如果每个书籍旁边有3列)以及书籍名称,图书馆名称以及是否可用。

1 个答案:

答案 0 :(得分:1)

有两种主要方法可以解决此问题:

  1. 使用聚合框架的$lookup让mongo为您将这些集合合并为一个结果:How to join multiple collections with $lookup in mongodb
  2. 使用应用程序端代码组合集合(这是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