未调用 Mongoose 中间件来执行 findByIdAndDelete

问题描述 投票:0回答:1
const mongoose = require('mongoose');
const { Schema } = mongoose;

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://127.0.0.1:27017/relationDatabase');
}

const orderSchema = new Schema({
    item: String,
    price: Number
});

const Order = mongoose.model("Order", orderSchema);

const customerSchema = new Schema({
    name: String,
    orders: [
        {
            type: Schema.Types.ObjectId,
            ref: "Order"
        }
    ]
});

const Customer = mongoose.model("Customer", customerSchema);

customerSchema.pre('findOneAndDelete',async ()=>{
    console.log("POST MIDDLEWARE");
});

customerSchema.post("findOneAndDelete",  async ()=>{
    console.log("POST MIDDLEWARE");
});

async function deleteCustomer() {
    const deletedCustomer = await Customer.findByIdAndDelete("6644eb4bc7df9bee46d64981");
    console.log(deletedCustomer);
}

let addCustomer=async ()=>{
    let cust1=new Customer({
        name:"john snow",
    })


    let order1=await Order.findOne({item:"burger"});
    let order2=await Order.findOne({item:"pasta"});

    cust1.orders.push(order1);
    cust1.orders.push(order2);

    let res=await cust1.save();

    console.log(res);
} 

deleteCustomer();

尝试调用 findOneAndDelete MDW 但它无法打印任何内容,因为它没有被调用我尝试直接使用 findOneAndDelete 但相同的结果不调用 MDW findOneAndDelete,我期待打印 console.log("POST MIDDLEWARE") 。

mongodb mongoose-schema
1个回答
0
投票

此案例有两个问题:

a) 编译模型后调用 pre() 或 post() 一般在 Mongoose 中不起作用,请参阅下面的链接 1。因此,请将语句的顺序更改为:

customerSchema.pre('findOneAndDelete',async ()=>{
    console.log("POST MIDDLEWARE");
});

customerSchema.post("findOneAndDelete",  async ()=>{
    console.log("POST MIDDLEWARE");
});

const Customer = mongoose.model("Customer", customerSchema);

b) findByIdAndDelete 没有等效的中间件,请在 findOneAndDelete 上编写中间件,请参阅下面的链接 2。

下面附有示例代码。

const mongoose = require('/usr/local/lib/node_modules/mongoose');
const { Schema } = mongoose;

run().catch((error) => console.log(error));

async function run() {

  await mongoose.connect('mongodb://127.0.0.1:27017/test');

  const someSchema = new Schema({ key1: String });
  someSchema.pre('findOneAndDelete', async function () {
    console.log('findOneAdDelete PRE middleware');
  });
  someSchema.post('findOneAndDelete', async function () {
    console.log('findOneAdDelete POST middleware');
  });

  const SomeModel = mongoose.model('SomeModel', someSchema);
  SomeModel.deleteMany();

  await SomeModel.findOneAndDelete({});
  const someId = new mongoose.Types.ObjectId();
  await SomeModel.findByIdAndDelete(someId);
}

Output:
findOneAdDelete PRE middleware
findOneAdDelete POST middleware
findOneAdDelete PRE middleware
findOneAdDelete POST middleware

链接:

1。在编译模型之前定义中间件

2。 Mongoose 预中间件与 findByIdAndDelete

© www.soinside.com 2019 - 2024. All rights reserved.