如何实现 type:(new mongoose.Schema) as Array

Posted

技术标签:

【中文标题】如何实现 type:(new mongoose.Schema) as Array【英文标题】:How to implement type:(new mongoose.Schema) as Array 【发布时间】:2019-09-03 22:23:25 【问题描述】:

我的 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);
);


当我尝试我的代码时 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"


和输出类似


    "_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】:

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

然后产品将作为一个对象数组来存储多个产品。

【讨论】:

你能不能给我更多的解释我不明白 @hend 我已经更新了我的答案,如果你仍然没有得到我想要的建议,请告诉我。 @hend 你明白了吗,我的建议是什么? 非常感谢您的询问并对我延迟重播感到抱歉 我觉得这里有更好的答案:***.com/a/25153874/861712

以上是关于如何实现 type:(new mongoose.Schema) as Array的主要内容,如果未能解决你的问题,请参考以下文章

如何实现 type:(new mongoose.Schema) as Array

JS new和instanceof的实现

如何根据json中的属性编写jackson反序列化器

python中的type和type.__new__有啥区别?

元编程:动态声明一个新结构

Go语言中new和 make的区别详解