首页 > 解决方案 > MongoDB - 保存子类别详细信息

问题描述

我想知道如何将我的产品详细信息(子类别)保存在订单详细信息中。就目前而言,MongoDB 只保存产品的 ID,不保存其详细信息。

订单模式:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Product = require('../models/Product').schema

let Order = new Schema ({
    _id: mongoose.Schema.Types.ObjectId,
    firstName: {type: String},
    lastName: {type: String},
    email:  {type: String},
    phone: {type: Number},
    address: {type: String},
    product: [{type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true}],
    createdAt:  {type: Date, default: Date.now}
},
{
    collection: 'orders'
}
);

module.exports = mongoose.model('Order', Order);

产品架构:

// define the table structure for mongoDB
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let Product = new Schema(
    {
         _id:{
            type: mongoose.Schema.Types.ObjectId
        },
        product_Name:{
            type: String
        },
        product_Description:{
            type: String
        },
        product_Price:{
            type: Number
        },
        product_Img:{
            type: String
        },
        product_Quantity: {
            type:Number
        },
        id:{
            type: Number
        },

    }, {
            collection: 'products'
        }
);

module.exports = mongoose.model('Product', Product);

订单路由(仅发布):

//create order
orderRoute.route('/').post((req, res) =>{
    Product.findById(req.body.productId)
    // .select('product')
    .populate('product')
    .then(product => {
        if(!product){
            return res.status(404).json({
                message: "product not found"
            });
        }
        const order = new OrderDetails({
            _id: new mongoose.Types.ObjectId(),
            product:req.body.productId,
            email: req.body.email,
            firstName:req.body.firstName,
            lastName: req.body.lastName,
            phone: req.body.phone,
            address: req.body.address,
        });
        return order.save()
        })
        
        .then(result => {
            console.log(result);
            
            return res.status(200).json({
                
                message: "Order was Created",
                
                order:result,
                request:{
                    type:"GET",
                    order_url: "http://localhost:5000/order/" + result._id
                }
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error:err.message
            });
        });
    
    });    

MongoDB文档:

在此处输入图像描述

**GET 方法返回完整详细的订单(来自 POSTMAN):

{
    "message": "Order was fetched",
    "order": {
        "product": [
            {
                "_id": "5e1c9fc052b6b1b6b8fee292",
                "product_Name": "Soccer Ball",
                "product_Description": "Soccer Ball",
                "product_Price": 20,
                "product_Img": "./assets/accessories/soccerball.jpg",
                "id": 0,
                "product_Quantity": 1,
                "type": "accessories"
            },
            {
                "_id": "5e5a6309d07a33280ce8c49d",
                "product_Name": "Air Pegasus 36",
                "product_Description": "Shoes 3",
                "product_Price": 80,
                "product_Img": "./assets/shoes/nike-mens air-zoom-pegasus-36-running-shoes.JPG",
                "id": 14,
                "product_Quantity": 1,
                "type": "shoes"
            }
        ],
        "_id": "5eadacbf1260955398655ff7",
        "email": "tal",
        "firstName": "hhhhh",
        "lastName": "hhhh",
        "phone": 123,
        "address": "tal",
        "createdAt": "2020-05-02T17:24:15.419Z",
        "__v": 0
    },
    "request": {
        "type": "GET",
        "all_orders_url": "http://localhost:5000/order"
    }

非常感激!

标签: node.jsangularmongodbroutes

解决方案


您可以通过嵌入文档来做到这一点。 https://docs.mongodb.com/manual/core/data-modeling-introduction/

这种方法称为去规范化,它会导致您在产品字段中出现数据重复,这在您的情况下可能需要,因为产品的价格可能会随着时间而变化,但如果您放弃产品集合,会使产品更难管理. 我建议您保留参考,但将任何可能更改的数据添加到订单详细信息集合中。


推荐阅读