有两个模型,ProductModel和分类模型.
目的:在创建一个产品(ProductModel)时,分别为其分配一个类别,类别集合中应该填充一个产品数组,但它们之间的连接不起作用.当创建一个产品(ProductModel)时,我通过json输出响应,它包含了除了category字段之外的所有字段,我还需要填写这个字段.
产品型号
import { Schema, model } from 'mongoose'
const ProductModel = new Schema({
productName: { type: String, required: true },
price: { type: Number, required: true },
preview: { type: String },
color: { type: String, required: true },
specs: {
images: [{ type: String }],
memory: { type: Number },
ram: { type: Number },
diagonal: { type: String },
},
category: {
name: String,
type: Schema.Types.ObjectId,
ref: 'Category',
},
})
export default new model('Product', ProductModel)
分类模型
import { Schema, model } from 'mongoose'
const 分类模型 = new Schema({
name: {
type: String,
required: true,
},
products: [
{
type: Schema.Types.ObjectId,
ref: 'Product',
},
],
})
export default new model('Category', 分类模型)
产品创建路由的逻辑
async post(req, res, next) {
try {
// Get fields from client
let { productName, price, preview, color, specs, category } = req.body
// Looking for a category transferred from a client
const productCategory = await 分类模型.find({ name: category })
console.log(productCategory)
// Creating product
const doc = new ProductModel({
productName,
price,
preview,
color,
specs,
category: productCategory._id,
})
// Save product
const product = await doc.save()
// Returning a response from the server to the client
return res.json(product)
} catch (error) {
console.log(error.message)
}
}
以下是我发送到服务器和从服务器接收的内容
Request:
{
"productName": "Air pods pro",
"price": 123,
"preview": "preview",
"color": "red",
"specs": {
"images": ["image1, image2, image3"],
"memory": 64,
"ram": 16,
"diagonal": "diagonal"
},
"category": "AirPods"
}
Response:
{
"productName": "Air pods pro",
"price": 123,
"preview": "preview",
"color": "red",
"specs": {
"images": [
"image1, image2, image3"
],
"memory": 64,
"ram": 16,
"diagonal": "diagonal"
},
"_id": "6609ad76341da85122e029d0",
"__v": 0
}
正如您所看到的,响应中没有类别字段,就像在数据库中一样,每个产品都缺少这个字段.Category集合中包含了一系列产品,也没有被填满
我会在下面附上截图