如何在获取模型数据时填充模型数据?Mongodb



我有两个模型的模式,其中一个是Category,另一个是subCategory。我们需要Category来创建一个子类别模型,但Category模型不必有subCategories。这是我的subCategory型号:

const Mongoose = require('mongoose');
const { Schema } = Mongoose;
// Brand Schema
const SubCategorySchema = new Schema({
name: {
type: String,
required:true
},
id: {
type:  Schema.Types.String,
unique:true,
required:true
},
category: {
type: Schema.Types.ObjectId,
ref: 'Category',
required:true
},
updated: Date,
created: {
type: Date,
default: Date.now
}
});
module.exports = Mongoose.model('SubCategory', SubCategorySchema);

这是我的Category型号:

const Mongoose = require('mongoose');
const { Schema } = Mongoose;
// Category Schema
const CategorySchema = new Schema({
name: {
type: String,
trim: true,
},
id: {
type: String,
required:true,
unique: true
},
image: {
type:String,
default:'http://res.cloudinary.com/wisecart/image/upload/v1616718691/kuy26lytx5k0lkvfkgrt.svg',
required:true
},
description: {
type: String,
trim: true
},
updated: Date,
created: {
type: Date,
default: Date.now
},
});
module.exports = Mongoose.model('Category', CategorySchema);

我正在使用当我请求一个类别时,如何填充子类别?例如,我想获得的响应

{
"image": "http://res.cloudinary.com/wisecart/image/upload/v1616718691/kuy26lytx5k0lkvfkgrt.svg",
"_id": "606605934b213d2887e3a840",
"name": "Samsung",
"description": "sama",
"id": "asa",
"subCategory": [{Subcategory with an Id of _id},{Subcategory with an Id of _id}],
"created": "2021-04-01T17:40:35.505Z",
"__v": 0
}

您必须使用aggregation查询

演示-https://mongoplayground.net/p/ItN9R9AlE4A

使用$lookup

对同一数据库中的未排序集合执行左外部联接,以从;加入";集合进行处理。$lookup阶段向每个输入文档添加一个新的数组字段;加入";收集$lookup阶段将这些重新整形的文档传递到下一阶段。

https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

db.category.aggregate([
{
"$lookup": {
"from": "subCategory", // collection name
"localField": "_id",
"foreignField": "category",
"as": "subCategory"
}
}
])

相关内容

  • 没有找到相关文章

最新更新