1

there are 2 collection book and category:

category Schema

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

Book schema

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

I want to fetch all book records with the category name instead of objectId of category schema.

  • Does this answer your question? [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb) Either use MongoDB's native `$lookup`(Can be used with mongoose as well) or mongoose's `.populate()`.. – whoami - fakeFaceTrueSoul May 17 '20 at 17:36

2 Answers2

1

Use populate()

books.find({})
     .populate('categoryId', 'type')
     .exec(...)
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

You want to read up on populate. Simply put it replaces your reference by objectId with the reverenced value. Then you have the category names in your populated book collection and can do a normal query.