如何将类型:(新mongoose.Schema)实现为数组

时间:2019-04-13 08:55:56

标签: arrays node.js mongodb mongoose

我在nodejs应用程序中有一个订单模型,需要在其中实现订单中要订购的产品数量。

我已将产品类型添加为(new mongoose.Schema)并由Joi验证,在这种情况下,我只能添加一个产品

这是订单模型

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
  }

  }));

还有Joi验证:

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);
  }

也是创建订单的路线

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);
});


当我通过邮递员尝试输入代码时

{
    "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"
}

和类似的输出

{
    "_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
}

这授予我添加一种产品的权限,但我需要在订单中添加多个产品

1 个答案:

答案 0 :(得分:0)

这样定义,创建新的object模式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
      }
});

将此方案分配到您的orderschemaproduct中。

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

然后,产品将充当存储多个产品的对象数组。