Я хотел бы знать, как я могу сохранить информацию о моем продукте (подкатегории) в деталях заказа. На данный момент MongoDB сохраняет только идентификатор продукта без подробных сведений.
Схема заказа:
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 do c:
** Метод 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"
}
Очень ценится!