你好我是mongodb和节点js的新手我有一个问题
这是我的产品架构
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
}
})
这是我的类别架构
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
}
})
我需要这样做; 每个产品数据必须具有类别
如果有一天,一个类别的名称发生了变化,那么与该类别相关的每个产品都必须更改
我正在尝试将类别ID设置为产品架构,当我获取数据时,每个产品的类别名称必须为json
如果你帮助我,我真的很困惑,我真的很感激答案 0 :(得分:0)
您可以将类别设置为:
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'category' //your model name
}
如果您想要多个类别,可以将其包装到数组中并将其命名为类别。
然后,当您获得数据时,您必须执行new Product().populate('category')
才能检索类别数据,而不是仅返回类别ObjectId。