<commit_before>'use strict';<commit_msg>Created cart order model.<commit_after>'use strict';

const mongoose = require('mongoose');
const CartProduct = require('./cart.js');
const createError = require('http-errors');
const debug = require('debug')('inventory:cart order');
const Schema = mongoose.Schema;

const cartOrderSchema = Schema({
  shippingAddress: {type: String, required: true},
  shippingName: {type: String, required: true},
  customerID: {type: Schema.Types.ObjectId, required: true},
  storeID: {type: Schema.Types.ObjectId, required: true},
  products: [{type: Schema.Types.ObjectId, ref: 'cartProduct'}]
});

const CartOrder = module.exports = mongoose.model('cartOrder', cartOrderSchema);

CartOrder.addCartProduct = function(id, product) {
  debug('addCartProduct');

  return CartOrder.findById(id)
  .then(order => {
    product.cartOrderID = order._id;
    this.tempOrder = order;
    return new CartProduct(product).save();
  })
  .then(product => {
    this.tempOrder.products.push(product._id);
    this.tempProduct = product;
    return this.tempOrder.save();
  })
  .then(() => this.tempProduct)
  .catch(err => Promise.reject(createError(404, err.message)));
};

CartOrder.removeCartProduct = function(id) {
  debug('removeCartProduct');

  return CartProduct.findById(id)
  .then(product => {
    this.tempProduct = product;
    return CartProduct.findByIdAndRemove(product._id);
  })
  .then(() => CartOrder.findById(this.tempProduct.cartOrderID))
  .then(order => {
    order.products.splice(order.products.indexOf(this.tempProduct._id), 1);
    order.save();
  })
  .catch(err => Promise.reject(createError(404, err.message)));
};
{'fraction_non_alphanumeric': 0.15995189416716776, 'fraction_numerical': 0.004209260372820205, 'mean_word_length': 4.985611510791367, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4469576', 'n_tokens_mistral': 518, 'n_tokens_neox': 516, 'n_words': 99}