簡體   English   中英

Nodejs Mongoose將額外數據添加到模型中

[英]Nodejs Mongoose Add extra data to model

這是產品型號:

const productSchema= new schema({
_id: {
    type: String,
    default: () => {return uniqid().toUpperCase()}
},
name: {
    type: String
},
price: {
    type: Number
},
type: {
    type: String
},
category: {
    type: String
},
sub_category: {
    type: String
},
images: {
    type: Array
},
sizes: {
    type: Array,
    default: ['OS']
},
materials: {
    type: Array
},
description: {
    type: String
},
weight: {
    type: String,
    default: ''
}
});

這是訂單模型:

let orderSchema = new schema({
products: [productModel],
});

在產品型號中,沒有quantity輸入,但我需要傳遞發送到訂單Api的每個產品的數量而不更改產品型號。

api調用的例子:

{
"products": [{
    "images": [
        "1",
        "2",
        "3"
    ],
    "sizes": [
        "OS"
    ],
    "materials": [
        "Cotton"
    ],
    "weight": "",
    "_id": "3EC65ISJWW6LU8C",
    "name": "Tshirt",
    "price": 10.99,
    "type": "Clothing",
    "category": "Men Tshirts",
    "description": "A Tshirt",
    "quantity": 5
},{
    "images": [
        "upload_7eb7af15fdaf27bff7667ee35ae4a8b0.png",
        "upload_7dea46a64b046f2d71a75612aaba1523.png",
        "upload_13422483a3b7406620b8e16c0d0ed7df.png"
    ],
    "sizes": [
        "OS",
        "Os2"
    ],
    "materials": [
        "Cotton",
        "M2"
    ],
    "weight": "",
    "_id": "3EC65ISJWW6LVLM",
    "name": "T-Shirt",
    "price": 10.99,
    "type": "Clothing",
    "category": "Men Tshirts",
    "description": "A Tshirt",
    "quantity": 5
}]
}

所以我添加了quantity條目,但它不在產品模型中。

這是我如何做到但它不起作用:

products: [productModel, {quantity: Number}],

您可以使用mongoose discriminators來擴展基礎架構

閱讀此文檔以獲取更多詳細信息

https://mongoosejs.com/docs/api.html#model_Model.discriminator

以下是文檔中描述的示例示例

function BaseSchema() {
  Schema.apply(this, arguments);

  this.add({
    name: String,
    createdAt: Date
  });
}
util.inherits(BaseSchema, Schema);

var PersonSchema = new BaseSchema();
var BossSchema = new BaseSchema({ department: String });

var Person = mongoose.model('Person', PersonSchema);
var Boss = Person.discriminator('Boss', BossSchema);
new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`

var employeeSchema = new Schema({ boss: ObjectId });
var Employee = Person.discriminator('Employee', employeeSchema, 'staff');
new Employee().__t; // "staff" because of 3rd argument above

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM