【发布时间】:2019-08-26 17:28:52
【问题描述】:
这是我的 MongoDB 架构:
const MenuSchema = new Schema({
name: {
type: String,
require: true
},
category: {
type: String,
require: true
},
description: {
type: String,
require: true
},
image: {
type: String,
},
caterer: {
type: Schema.Types.ObjectId,
ref: 'User'
},
products: [{
type: Schema.Types.ObjectId,
ref: 'Product'
}]
}, { timestamps: true })
const ProductSchema = new Schema({
name: {
type: String,
require: true
},
category: {
type: String,
require: true
},
description: {
type: String,
require: true
},
image: {
type: String,
},
price: {
type: String
}
}, { timestamps: true })
我想知道的是如何在删除主“菜单”文档的同时删除产品数组?当我删除Menu时,我也可以假设属于菜单的products应该被删除。
目前这是我删除菜单(并尝试删除其产品)的方式:
await Menu.findOneAndDelete({ _id: req.params.menu_id }, (err, response) => {
if (err) {
console.error(err);
}
Product.remove({ _id: { $in: req.body.products }}, (err, res) => {
if (err) {
console.error(err);
}
console.log('Deleted products');
});
});
但是,产品不会被删除。有什么建议吗?
【问题讨论】:
-
Product.remove({ _id: req.body.products })就足够了,但要确保它是 ids 数组
标签: node.js mongodb mongoose mongoose-populate