如何使用Mongoose删除中间件级联删除? [英] How to cascade delete using Mongoose remove middleware?

查看:89
本文介绍了如何使用Mongoose删除中间件级联删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当DELETE请求发送到我的API时,我正在尝试删除模式的所有依赖项.删除可以,但是应该清除依赖项的可删除中间件似乎甚至没有被调用.

I'm trying to delete all dependencies of a schema when a DELETE request is sent to my API. Deleting goes ok, but the remove middleware, which is supposed to clean the dependencies, seems like is not even getting called.

这是我的客户模式:

var mongoose = require("mongoose"),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');

var Order = require('./order');
var Customer = new Schema({
    name: String,
    telephone: Number,
    address: String,
    email: String,
    seller: String
});

Customer.post('remove', function(next) {
    Order.remove({ customer: this._id }).exec();
    next();
});

Customer.plugin(passportLocalMongoose);

module.exports = mongoose.model("Customer", Customer);

这是我的客户路线:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var isAuthenticated = require('./isAuthenticated');
var Customer = require('../models/customer');
var Order = require('../models/order');

// (...)

router.delete('/:customer_id', function(req, res) {
    Customer.remove({ _id: req.params.customer_id }, function(err) {
        if (err)
            res.json({ SERVER_RESPONSE: 0, SERVER_MESSAGE: "Error deleting", ERR: err });
        else res.json({ SERVER_RESPONSE: 1, SERVER_MESSAGE: "Customer deleted" });
    });
});

// (...)

我确实看过这个问题和猫鼬文档(

I did look this question and Mongoose Docs (Mongoose Middleware) but it's still unclear to me. I don't know what I'm missing or doing wrong.

提前谢谢!

编辑

这是我的项目存储库.请随意查看.

推荐答案

我终于找到了解决方案.中间件没有触发,因为您必须在模型实例上使用remove()save()等,而不是模型本身.

I finally found the solution to this. Middleware wasn't firing because you must use remove(), save(), etc on model instances, not the model itself.

示例:

Customer.remove({...});无法正常工作.

Customer.findOne({...}, function(err, customer) {
  customer.remove();
});

将起作用,并且将执行Customer.post('remove')中的所有操作.

will work and will do whatever is in Customer.post('remove').

这篇关于如何使用Mongoose删除中间件级联删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆