[英]Mongoose One-to-Many, How to get field value of category
我有 2 个收藏:类别和书籍
书:
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}}
?**
由于您使用的是 Mongoose,因此可以使用populate()
方法。 你可以这样做:
const books = await Books.find().populate('category')
Book.aggregate([{
$lookup: {
from: "Category",
localField: "category",
foreignField: "_id",
as: "category"
}
}]).exec(function(err, students) {
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.