我有两个模型Products
和Purchases
,“购买”是指产品。
现在,我要创建一个删除函数delete Products
和所有引用的Purchases
。
product.js模型
var productSchema = new Schema({
name: String,
id_num: String,
start_inv: Number,
date_added: { type: Date, default: Date.now },
purchases: [{ type: Schema.Types.ObjectId, ref: 'Purchases' }],
});
purchase.js模型
var purchaseSchema = new Schema({
received: Number,
purchases_date: { type: Date, default: Date.now },
});
删除路线
router.delete('/', (req, res) => {
Product.findByIdAndRemove(req.params.id, (err, product) => { // product remove working
Purchases.deleteMany({ _id: { $in: product.purchases } }, function (err, response) { // working but not deleting Purchases
const data = {
message: "Product successfully deleted",
id: product._id
};
res.status(200).send(data);
});
});
})
数据
[
{
"purchases": [
"5dbbb5b5b5ae3d34a82f649c"
],
"_id": "5dbbb599b5ae3d34a82f649b",
"name": "z1",
"id_num": "z1",
"start_inv": 100,
"date_added": "2019-11-01T04:33:29.952Z",
"__v": 1
}
]
这在执行后仍然有效,但是它只会删除Product
,而不会删除Purchases
停留数小时的问题。