【问题标题】:how to join two collection in mongodb如何在mongodb中加入两个集合
【发布时间】:2020-09-03 06:20:09
【问题描述】:

有2个收藏书和类别:

类别架构

Category = mongoose.Schema({
    categoryName: {
        type: String,
        require: true
    },
    isActive: {
        type: Boolean
    }
});

图书架构

const Book = mongoose.Schema({
    categoryId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'category',
        require: true
    },
    bookName: {
        type: String,
        require: true,
    },
    bookAuthor: {
        type: String,
        require: true,
    },
    bookPrice: {
        type: Number,
        require: true,
    },
    bookLanguage: {
        type: String,
        require: true,
    }
});

我想使用类别名称而不是类别架构的 objectId 获取所有书籍记录。

【问题讨论】:

标签: mongodb mongoose nosql


【解决方案1】:

使用populate()

books.find({})
     .populate('categoryId', 'type')
     .exec(...)

【讨论】:

    【解决方案2】:

    您想阅读有关填充的内容。简单地说,它用受尊敬的值替换您的 objectId 引用。然后,您就可以在已填充的图书收藏中获得类别名称,并且可以进行正常查询。

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 2012-09-15
      • 2020-05-12
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多