POST массив продуктов - PullRequest
       15

POST массив продуктов

0 голосов
/ 04 мая 2020

Мне было интересно, возможно ли опубликовать массив идентификаторов продуктов и показать их детали, потому что, как вы можете видеть ниже, отображается только первый продукт.

Почтальон:

{
	"productId":["5e1c9fc052b6b1b6b8fee292", "5e5a6309d07a33280ce8c49d"],
	"firstName":"hhhhh",
    "lastName": "hhhh",
    "email":  "tal",
    "phone": "123",
    "address": "tal"
}

Ответ почтальона:

{
    "message": "Order was Created",
    "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": "5eb005629fe7ab3f04a9c9a1",
        "email": "tal",
        "firstName": "hhhhh",
        "lastName": "hhhh",
        "phone": 123,
        "address": "tal",
        "createdAt": "2020-05-04T12:06:58.174Z",
        "__v": 0
    },
    "request": {
        "type": "GET",
        "order_url": "http://localhost:5000/order/5eb005629fe7ab3f04a9c9a1"
    }
}

Схема заказа:

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:Product, ref: 'Product', required: true}],
    // product: [{type:mongoose.Schema.Types.ObjectId, ref: 'Product', 
     required: true}],
    product_Name:[{type:String,required: true}],
    // product_Description:{type:Product.product_Description},
    // product_Price:{type:Product.product_Price},
    // id:{type:Product.id},
    createdAt:  {type: Date, default: Date.now}
},
{
    collection: 'orders'
}
);

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

Маршрутизация заказа:

//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:[product],
            // 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
            });
        });
    
    });   

В маршрутизации заказа, используя product: req.body.productId вместо product: [product] ответ был массив идентификаторов, но без подробностей. Почему это?

    "message": "Order was Created",
    "order": {
        "product": [
            "5e1c9fc052b6b1b6b8fee292",
            "5e5a6309d07a33280ce8c49d"
        ],

Очень ценится!

1 Ответ

0 голосов
/ 04 мая 2020
orderRoute.route('/').post((req, res) => {
  const productIDs = req.body.productId;
  const order = new OrderDetails({
    product: productIDs,
    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 => {
      result.populate("product").then(order => {
        console.log(order);
        return res.status(200).json({
          message: "Order was Created",
          order,
          request: {
            type: "GET",
            order_url: "http://localhost:5000/order/" + result._id
          }
        });
      }).catch(err => {
        console.log(err);
        res.status(500).json({
          error: err.message
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err.message
      });
    });
});
...