更改mongoose模式viewModel

时间:2017-07-31 20:40:11

标签: node.js mongodb mongoose

我在mongoose中遇到相关架构的问题: 我有3个架构:

var recipeProductSchema = new mongoose.Schema({
    product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
    productWeight: Number
}, {toJSON: {virtuals: true}});

var recipeSchema = new mongoose.Schema({
    name: String,
    products: [RecipeProduct]
})

var productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    weight: {
        type: Number,
        required: true
    },
    price: {
        type: Number,
        required: true
    }
})

当我想用我发送的产品创建配方时:

{
    "name": "Cake",
    "products": [
        {
            "product": "597a517b7c2e8508c8cc3f3a",
            "productWeight": 50
        }
    ]
}

但是当我得到关于食谱的细节时,我得到了这个:

{
    "_id": "597f7d0ce25d1413149aa30d",
    "name": "Cake",
    "products": [
        {
            "product": {
                "_id": "597a517b7c2e8508c8cc3f3a",
                "name": "Sugar",
                "weight": 400,
                "price": 40
            },
            "productWeight": 50,
            "_id": "597b825a61736b1adcb0ed0f",
            "productPrice": "5.00",
            "id": "597b825a61736b1adcb0ed0f"
        }
    ]
}

是否有可能让这两个json彼此相似? 因为在编辑配方视图中我不希望在数据发送之前更改配方的产品对象;

我想发送这个json:

{
    "name": "Cake",
    "products": [
        {
            "product": {
                "id": "597a517b7c2e8508c8cc3f3a" // or "_id"
            },
            "productWeight": 50
        }
    ]
}

我想得到:

{
    "_id": "597f7d0ce25d1413149aa30d",
    "name": "Cake",
    "products": [
        {
            "product": {
                "_id": "597a517b7c2e8508c8cc3f3a",
                "name": "Sugar",
                "weight": 400,
                "price": 40
            },
            "productWeight": 50,
            "_id": "597f7d0ce25d1413149aa30e",
            "productPrice": "5.00",
            "id": "597f7d0ce25d1413149aa30e"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

尝试做孩子/父母关系

var recipeProductSchema = new mongoose.Schema({
    product: [productSchema],
    productWeight: Number
}, {toJSON: {virtuals: true}});

var recipeSchema = new mongoose.Schema({
    name: String,
    products: [recipeProductSchema]
})

var productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    weight: {
        type: Number,
        required: true
    },
    price: {
        type: Number,
        required: true
    }
})

并在您的创建函数中执行$push

你也可以在你的get函数中使用mongoose populate