有两个模型,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集合中包含了一系列产品,也没有被填满

我会在下面附上截图

Mongo. Mongo.

推荐答案

在你的ProductModel模式中,category属性有一个name属性给它.这表明你希望category是一个有name属性的Object.我想那不是你的本意.你需要删除它,以便category只是一个值类型为ObjectId的属性.

const ProductModel = new Schema({
    //...
    category: {
        name: String, //< delete this
        type: Schema.Types.ObjectId,
        ref: 'Category',
    },
})

要将product._id放入productCategory.products数组,您需要手动将其推入数组,如下所示:

const productCategory = await CategoryModel.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()

// Now save product._id into productCategory.products array
productCategory.products.push(product._id);
await productCategory.save();

// Returning a response from the server to the client
return res.json(product)

Javascript相关问答推荐

Next.js Next/Image图像隐含性有任何类型-如何修复?

D3多线图显示1线而不是3线

是什么原因导致此Angular 16应用程序中类型错误时属性结果不存在?

Vega中的模运算符

在React中获取数据后,如何避免不必要的组件闪现1秒?

模块与独立组件

我开始使用/url?q=使用Cheerio

为什么我的列表直到下一次提交才更新值/onChange

如何通过将实例方法的名称传递给具有正确类型的参数的继承方法来调用实例方法?

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

闭包是将值复制到内存的另一个位置吗?

Eval vs函数()返回语义

更新动态数据中对象或数组中的所有值字符串

使用Nuxt Apollo在Piniastore 中获取产品细节

如何 for each 输入动态设置输入变更值

面对代码中的错误作为前端与后端的集成

如果没有页面重新加载Angular ,innerHTML属性绑定不会更新

按什么顺序接收`storage`事件?

使用CEPRESS截取时,cy.Wait()在等待5000ms的第一个路由请求时超时

当一条路由在Reaction路由中命中时,如何有条件地渲染两个组件或更改两个插座?