hello i am new on mongodb and node js i have a question
你好,我是mongodb和节点js的新人,我有一个问题
here is my product schema
这是我的产品架构
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const categorySchema = require('./category');
const ProductSchema = new Schema({
country: {
type: String,
required: [true, "country can't be null"]
},
city: {
type: String,
default: ""
},
name: {
type: String,
required: [true, "name can't be null"]
},
measureValue: {
type: Number,
default: 0
},
minPrice: {
type:Number,
required: [true, "minPrice can't be null"],
min: [1,"minPrice must be at least 1"]
},
maxPrice: {
type:Number,
required: [true, "maxPrice can't be null"],
min: [1,"maxPrice must be at least 1"]
},
photoUrl: {
type:String,
default: ""
},
explanation: {
type: String,
default: ""
},
category: [categorySchema.schema],
userID: {
type: String,
required: [true,"userid cant be null"]
},
isActive: {
type: Boolean,
default: true
},
createdDate: {
type: Date,
default: Date.now
},
deletedDate: {
type:Date
}
})
and here is my category schema
这是我的类别架构
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
name: {
type: String,
required: [true, "name can't be null"]
},
createdDate: {
type: Date,
default: Date.now
},
deletedDate: {
type:Date
}
})
i need to do this; every product data must be have category
我需要这样做;每个产品数据都必须有类别
if one day,one category's name changed then every product that relation with that category must changed
如果有一天,一个类别的名称发生了变化,那么与该类别相关的每个产品都必须更改
i am trying to set category id to product schema and when i fetch the data it must be comes every product with category name as json
我正在尝试将类别ID设置为产品架构,当我获取数据时,它必须是每个产品的类别名称为json
i am really confused if you help me i'd be really thankful
如果你帮助我,我真的很困惑,我真的很感激
1 个解决方案
#1
0
You can set up your category as :
您可以将类别设置为:
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'category' //your model name
}
You can wrap it into an array and name it categories if you want multiple categories.
如果需要多个类别,可以将其包装到数组中并将其命名为类别。
Then when you get the data, you will have to execute new Product().populate('category')
to get retrieve the category data instead of just returning the category ObjectId.
然后,当您获得数据时,您将必须执行新的Product()。populate('category')以获取类别数据,而不是仅返回类别ObjectId。
#1
0
You can set up your category as :
您可以将类别设置为:
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'category' //your model name
}
You can wrap it into an array and name it categories if you want multiple categories.
如果需要多个类别,可以将其包装到数组中并将其命名为类别。
Then when you get the data, you will have to execute new Product().populate('category')
to get retrieve the category data instead of just returning the category ObjectId.
然后,当您获得数据时,您将必须执行新的Product()。populate('category')以获取类别数据,而不是仅返回类别ObjectId。