我有一个 ProductsGroup 模型,它将产品分组到一个变体数组中。更新 ProductsGroup 后,我更新了产品中的 productGroup 属性(效果很好)。然后,我尝试从以前的 ProductsGroup.variants 数组中删除更新的产品,但这部分不起作用。更新后,我有两个 ProductsGroups 中的产品,而不仅仅是更新后的一个。
这是我的模式
Product.js
const { Schema } = mongoose
const ImageSchema = new Schema({
url: String,
filename: String
});
ImageSchema.virtual('thubnail').get(function () {
return this.url.replace('/upload', '/upload/w_200')
})
const ProductSchema = new Schema({
name: String,
images: [ImageSchema],
description: String,
metaDescription: String,
priceN: Number,
priceB: Number,
SKU: String,
variant: String,
allegroUrl: String,
isRecommended: Boolean,
isOnSale: Boolean,
isBestseller: Boolean,
isNewProduct: Boolean,
productGroup: { type: Schema.Types.ObjectId, ref: 'ProductsGroup' }
})
ProductSchema.pre(
'updateMany', async (doc) => {
if (doc) {
const ProductsGroup = require('./productsGroup')
const pg = await ProductsGroup.updateMany(
{
variants: doc._id
},
{
$pullAll: {
variants: doc._id
}
})
}
}
)
module.exports = mongoose.model('Product', ProductSchema);
ProductsGroup.js
const { Schema } = mongoose;
const Product = require('./product')
const ImageSchema = new Schema({
url: String,
filename: String
});
ImageSchema.virtual('thubnail').get(function () {
return this.url.replace('/upload', '/upload/w_200')
})
const ProductsGroupSchema = new Schema({
name: String,
image: ImageSchema,
variants: [{ type: Schema.Types.ObjectId, ref: 'Product' }]
})
ProductsGroupSchema.post(
'save', async (doc, next) => {
if (doc) {
await Product.updateMany (
{
_id: {
$in: doc.variants
}
},
{
$set: { productGroup: doc._id }
})
}
next()
}
// ! remove variant id after includes to new pg
)
module.exports = mongoose.model('ProductsGroup', ProductsGroupSchema);