为什么在创建时无法推送ref数组?猫鼬

时间:2018-09-19 23:25:46

标签: arrays mongoose schema push

我正在尝试将ref的数组与其他info一起推送,以某种方式无法正常工作,即使创建$push之后我也必须在创建后进行更新代码是相同的。

例如,这两种模式

const ProductSchema = new Schema(Object.assign({
    name: {type: String};
});

const ModelSchema = new Schema(Object.assign({
    products: [
        {
            product: { type: Schema.Types.ObjectId, ref: 'Products' },
            amount: { type: Number },
            price: { type: Number },
            discount: { type: Number },
            tax: { type: Number },
            total: { type: Number },
        }
    ],

}), { timestamps: true });

我在这样的数组中有两个产品,我正尝试将它们传递到ref

const calProducts = [
    {
        id: "3283982388382938", // this is the product's id
        amount: 234,
        price: 234,
        discount: 0,
        tax: 0,
        total: 468
    },
    {
        id: "3283982382282938", // this is the product's id
        amount: 234,
        price: 234,
        discount: 0,
        tax: 0,
        total: 468
    }
];

const newProducts = {
        $push: { products: { $each: calProducts } }  // suppose this should work
    };

const newModel = new ModelSchema(newProducts);
newModel.save();

以某种方式创建了newModel,但product字段为products: []

我必须进行更新,例如

const m = ModelSchema.findOneAndUpdate({
    _id = newModel._id
}, {
    $push: { products: { $each: calProducts } }  //  this is exactly the same code, but this works though
});

现在我回头看看newModel,最后products字段不再为空。

我到底缺少什么? 预先感谢您的帮助。

0 个答案:

没有答案