Nodejs Mongoose向模型添加额外的数据

时间:2019-06-18 16:26:20

标签: javascript node.js mongoose

这是产品型号:

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}],

1 个答案:

答案 0 :(得分:0)

您可以使用猫鼬识别符来扩展基本架构

浏览此文档以获取更多详细信息

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