Mongoose pre('save')预函数未调用,locationId自增功能失效求助
排查Mongoose pre('save')钩子未触发&locationId自增失效的问题
先看你代码里的几个核心问题,这些直接导致了钩子没执行、自增逻辑失效:
1. Schema定义与钩子挂载顺序完全搞反了
你现在是先写了locationSchema.pre('save')钩子,然后才定义locationSchema——这根本行不通!钩子必须挂载到已经创建好的Schema实例上。得先定义Schema,再给它加预钩子。
错误顺序:
// ❌ 先挂钩子,后定义schema,钩子找不到挂载目标 locationSchema.pre('save', function(next) { ... }) const locationSchema = mongoose.Schema({ ... })
正确顺序:
// ✅ 先定义schema const locationSchema = mongoose.Schema({ locationId:{ type:Number, unique:true } }); // ✅ 再挂载pre钩子 locationSchema.pre('save', function(next) { console.log(" HELLO ") // 现在应该能正常打印了 var doc = this; Counter.findByIdAndUpdate({_id: 'location_id'}, {$inc: {seq: 1} }, {upsert: true , new: true}, function(error, counter) { if(error) return next(error); doc.locationId = counter.seq; next(); }); });
2. Mongoose模块导入顺序错误
看你locationSchema的代码:你先调用了mongoose.Schema(),然后才require('mongoose')——这在Node.js里会直接抛出ReferenceError: mongoose is not defined(除非你实际代码顺序不是这样,但你写出来的顺序绝对错误)。必须先导入mongoose,再创建Schema:
正确顺序:
const mongoose = require('mongoose') // 然后再定义schema const locationSchema = mongoose.Schema({ locationId:{ type:Number, unique:true } });
3. 额外检查点:确保使用能触发save钩子的方法
如果你用Location.insertMany()批量插入文档,pre('save')是不会触发的——因为insertMany绕开了单个文档的save流程。这种情况要么改用Location.create()(单个/多个文档都支持,会触发save钩子),要么单独处理批量插入的自增逻辑。
4. 计数器模型的引用问题
你把counterModel导出到了另一个模块,要确保在locationSchema的模块里正确导入了它,不然Counter.findByIdAndUpdate会找不到模型:
// 在locationSchema所在文件顶部导入计数器模型 const { counterModel: Counter } = require('./path/to/your/counter-module')
修正后的完整示例代码
// 先导入mongoose const mongoose = require('mongoose') // 导入计数器模型 const { counterModel: Counter } = require('./counter') // 定义locationSchema const locationSchema = mongoose.Schema({ locationId:{ type:Number, unique:true } }); // 挂载pre('save')钩子 locationSchema.pre('save', function(next) { console.log(" HELLO ") // 现在应该能正常打印了 const doc = this; Counter.findByIdAndUpdate( {_id: 'location_id'}, {$inc: {seq: 1} }, {upsert: true , new: true}, function(error, counter) { if(error) return next(error); doc.locationId = counter.seq; next(); } ); }); // 创建Location模型 const Location = mongoose.model('Location', locationSchema) module.exports = Location
按上面的步骤修正后,你的pre('save')钩子应该能正常触发,locationId的自增逻辑也能正常运行了。
内容的提问来源于stack exchange,提问作者Rana
相关产品推荐
相关产品推荐

