Hend Mohammed
Hend Mohammed

Reputation: 129

How to implement type:(new mongoose.Schema) as Array

I have a model for order in my nodejs Application and need to implement in it the number of products which will be in the order.

I have Added The Product type as (new mongoose.Schema) and validate it by Joi, in this case, I can Only add one Product

here is the model of order

const Order = mongoose.model('Order', new mongoose.Schema({
  Name: {
    type: String,
    required: true,
    minlength: 3,
    maxlength: 50
  },  
  OrderDate: {
    type: Date,
    default : Date.now
  },
  Address: {
    type: String,
    minlength: 3,
    maxlength: 50,
    required: true,
  },
  City: {
    type: String,
    minlength: 3,
    maxlength: 50,
    required: true,
  },
  Phone: {
    type:Number,
    required: true
  },
  Payment: {
    type:String,
    required: true
  },
  OrderPrice: {
    type:String,
    required: true
  },
  ShippingPrice:{
    type:Number
  },
  customer: {
    type: new mongoose.Schema({
      UserName: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50
      },
      Email: {
        type: String,
        unique : true,
        required: true,
        minlength: 5,
        maxlength: 255
      },Phone: {
        type: Number,
        required: true,
        min :10 
      },
      Address: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50
      }
    }),  
    required: true
  },
  product:
     {
    type: new mongoose.Schema({
    Pro_Name: {
      type: String,
      required: true,
      minlength: 5,
      maxlength: 50
    },
    Pro_Price: {
      type: Number,
      required: true
      },
    Pro_IMG: {
        type: String,
        minlength: 5,
        maxlength: 50
      },
    // Pro_Qty: {
    //   type: Number,
    //   min: 1
    //   }
    }),
    require: true
  }

  }));

And The Joi validation :

function validateOrder(order) {
    const schema = {
      Name: Joi.string().min(3).required(),
      Address: Joi.string().required(),
      City: Joi.string().required(),
      Phone: Joi.number().required(),
      Payment: Joi.string().required(),
      OrderPrice: Joi.number().required(),
      customerID:Joi.objectId(),
      productID:Joi.objectId(),

    };

    return Joi.validate(order, schema);
  }

Also the rout for creating the order

router.post('/', async(req, res)=>{     
    const {error} = validate(req.body);
    if (error) return res.status(404).send(error.details[0].message);

    const customer = await Customer.findById(req.body.customerID);
    if (!customer) return res.status(400).send('Invalid customer Pleas Login First.');

    const product = await Product.findById(req.body.productID);
    if (!product) return res.status(400).send('Invalid Product to be add in the cart');

    //create the new Product
    let newOrder = new Order({ 
        Name: req.body.Name,
        Address: req.body.Address,
        City: req.body.City,
        Phone: req.body.Phone,
        Payment: req.body.Payment,
        OrderPrice: req.body.OrderPrice,
        customer: {
            _id: customer.id,
            UserName: customer.UserName,
            Email:customer.Email,
            Phone:customer.Phone,
            Address:customer.Address
        },
        product: {
            _id: product.id,
            Pro_Name: product.Pro_Name,
            Pro_Price:product.Pro_Price,
            Pro_IMG:product.Pro_IMG
        }
    });

    // try{
    //     new Fawn.Task()
    //       .save('orders' , newOrder)
    //       .update('product' , {_id:Product._id},{
    //         $inc: {numberInStock : -1 }
    //       })
    //       .run();
    //     res.send(newOrder);
    //   }
    //    catch(ex){
    //      res.status(500).send('Somthing bad has happend -_-.')
    //    }


    newOrder = await newOrder.save();

    res.send(newOrder);
});


When I Try My Code by Postman The Input

{
    "Name": "Hend Mohammed",
    "Address": "This is Forth adress",
    "City": "Giza",
    "Phone": 12345689,
    "Payment": "By HEND ^_^ With products and data a bout the customer",
    "OrderPrice": 50000,
    "customerID":"5cb18f625a9de34582475b22",
    "productID" :"5ca11d5f9456812c79d21be6"
}

and The output like

{
    "_id": "5cb1a3b7c05d72523925bbac",
    "Name": "Hend Mohammed",
    "Address": "This is Forth adress",
    "City": "Giza",
    "Phone": 12345689,
    "Payment": "By HEND ^_^ With products and data a bout the customer",
    "OrderPrice": "50000",
    "customer": {
        "_id": "5cb18f625a9de34582475b22",
        "UserName": "heba Mohammed",
        "Email": "hebs47852@gmail.com",
        "Phone": 12345678910,
        "Address": "1235Adress"
    },
    "product": {
        "_id": "5ca11d5f9456812c79d21be6",
        "Pro_Name": "Cake updated",
        "Pro_Price": 100,
        "Pro_IMG": "Cake Image"
    },
    "OrderDate": "2019-04-13T08:54:15.994Z",
    "__v": 0
}

This Give me permission to add one product But I need To add more than one product in the Order

Upvotes: 0

Views: 717

Answers (1)

Amol B Jamkar
Amol B Jamkar

Reputation: 1257

Define like this, create new object schema productSchema

const productSchema = new mongoose.Schema({
    Pro_Name: {
      type: String,
      required: true,
      minlength: 5,
      maxlength: 50
    },
    Pro_Price: {
      type: Number,
      required: true
      },
    Pro_IMG: {
        type: String,
        minlength: 5,
        maxlength: 50
      }
});

Assign this scheme into your orderschema to product.

const model = new mongoose.Schema({
  Product: [productSchema] <-- it will be as a array of objects
});
const Order = mongoose.model("Order", model);

Product then will act as a Array of object to store multiple products.

Upvotes: 1

Related Questions