-
From the middleware documentation:
So I think For example: import mongoose from 'mongoose';
import { config } from '../../config';
mongoose.set('debug', true);
console.log(mongoose.version);
const reviewSchema = new mongoose.Schema({});
reviewSchema.post('deleteOne', function () {
console.log('post deleteOne');
});
reviewSchema.post('updateOne', function () {
console.log('post updateOne');
});
const Review = mongoose.model('Review', reviewSchema);
(async function main() {
try {
await mongoose.connect(config.MONGODB_URI);
// seed
const [r1] = await Review.create([{}, {}]);
// test
// updateOne
await r1?.updateOne({ name: 'teresa teng' }); // works
await Review.updateOne({ _id: r1?._id }, { name: 'teresa teng' }); // works
// deleteOne
await Review.deleteOne({ _id: r1?._id }); // works
await r1?.deleteOne(); // doesn't work
} catch (error) {
console.error(error);
} finally {
await mongoose.connection.close();
}
})(); Logs: 7.4.0
Mongoose: reviews.insertOne({ _id: ObjectId("64b771cc02ca30b633518b8e"), __v: 0 }, {})
Mongoose: reviews.insertOne({ _id: ObjectId("64b771cc02ca30b633518b8f"), __v: 0 }, {})
post updateOne
post updateOne
Mongoose: reviews.deleteOne({ _id: ObjectId("64b771cc02ca30b633518b8e") }, {})
post deleteOne
Mongoose: reviews.deleteOne({ _id: ObjectId("64b771cc02ca30b633518b8e") }, { session: null }) Is this a bug or am I missing something? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
change your post function to reviewSchema.post('deleteOne', {document: true, query: true}, function () {
console.log('post deleteOne');
}); |
Beta Was this translation helpful? Give feedback.
Unfortunately the default behavior is slightly different between
updateOne
anddeleteOne
, and we have tests that assert on this behavior. But we will change this behavior in 8.x, see #13660, specifically this test file: https://github.com/Automattic/mongoose/pull/13660/files#diff-7b7bf89c426b1b002315ff19e892ac3a7750e57ed11ad563074b4e200fad218e. Will update our docs.