猫鼬One-to-Many,如何获取类别的字段值

Mongoose One-to-Many, How to get field value of category

我有 2 collection: 类别和书

图书:

      const mongoose = require('mongoose');
        // eslint-disable-next-line camelcase
        const mongoose_delete = require('mongoose-delete');
        
        const { Schema } = mongoose;
        const SchemaTypes = mongoose.Schema.Types;
        const Book = new Schema({
          name: { type: String },
          price: { type: Number },
          images: { type: Array },
          country: { type: String },
          author: { type: String },
          publicationDate: { type: String },
          description: { type: String },
          category: { type: SchemaTypes.ObjectId, ref: 'Category' },
          date: { type: Date, default: Date.now },
        }, {
          timestamps: true,
        });
        Book.plugin(mongoose_delete);
        Book.plugin(mongoose_delete, { overrideMethods: 'all', deletedAt: true });
        module.exports = mongoose.model('Book', Book);

类别:

      const mongoose = require('mongoose');
        // eslint-disable-next-line camelcase
        const mongoose_delete = require('mongoose-delete');
        
        const SchemaTypes = mongoose.Schema.Types;
        const { Schema } = mongoose;
        
        const Category = new Schema({
          name: { type: String, required: true },
          image: { type: String },
          products: [{ type: SchemaTypes.ObjectId, ref: 'Book' }],
          date: { type: Date, default: Date.now },
        }, {
          timestamps: true,
        });
        Category.plugin(mongoose_delete);
        Category.plugin(mongoose_delete, { overrideMethods: 'all', deletedAt: true });
        module.exports = mongoose.model('Category', Category);

我select收到的书全部上榜:

      {
        _id: new ObjectId("623668ac5b1d392b37690cbc"),
        name: 'The Godfather',
        price: 110000,
       
        country: 'U.S',
        publicationDate: '1969',
        category: new ObjectId("6238fdf64f60303756b60b20"),
        author: 'Mario Puzo',
        ... : ...

}

而且我想在产品列表中显示类别名称,我该怎么做? **喜欢:{{book.category.name}}

{{book.category.image}}

?**

尝试$lookup (aggregation)

Book.aggregate([{
    $lookup: {
        from: "Category", 
        localField: "category",
        foreignField: "_id",
        as: "category"
    }
}]).exec(function(err, students) {
   
});

由于您使用的是 Mongoose,因此可以使用 populate() 方法。你可以这样做:

const books = await Books.find().populate('category')