代码之家  ›  专栏  ›  技术社区  ›  asd qwe

如何链接猫鼬中的两个模型?

  •  1
  • asd qwe  · 技术社区  · 1 年前

    有两种模型,ProductModel和CategoryModel。

    目的:创建产品(ProductModel)时,分别为其分配一个类别,类别集合中应该填写一个产品数组,但它们之间的连接不起作用。创建产品(ProductModel)时我通过json输出响应,它包含除类别字段外的所有字段,我也需要填写此字段。

    产品型号

    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 CategoryModel = new Schema({
        name: {
            type: String,
            required: true,
        },
        products: [
            {
                type: Schema.Types.ObjectId,
                ref: 'Product',
            },
        ],
    })
    
    export default new model('Category', CategoryModel)
    

    产品创造路线的逻辑

      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 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()
    
                // 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

    1 回复  |  直到 1 年前
        1
  •  0
  •   jQueeny    1 年前

    在您的 ProductModel 架构 category 属性具有 name 给它的财产。这表明你想要 类别 成为具有的对象 名称 所有物我认为那不是你的本意。你需要去掉它,这样 类别 只是值为类型的属性 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)