如何在Mongoose Schema中定义默认函数?解决Promise pending报错
解决方案
Mongoose的字段default选项不支持异步函数返回Promise,它会直接把Promise对象当作字段值,这就是你看到"Promise {
要实现save()时自动计算填充friendlyId,别用default,改用Mongoose的pre-save中间件,步骤如下:
- 先调整字段定义,去掉
default和强制required(中间件会自动填充,不需要用户传入):
friendlyId: { type: Number, unique: true, index: true }
- 给模型添加
pre('save')中间件,在保存前计算赋值:
yourSchema.pre('save', async function(next) { // 只有字段未设置时才生成,避免更新时覆盖已有值 if (!this.friendlyId) { try { const count = await mongoose.model(collectionName).countDocuments({}); this.friendlyId = count + 1; next(); } catch (error) { logError(error); next(error); } } else { next(); } });
注意点
- 这种基于
countDocuments的方式在高并发场景下可能出现重复值——两个请求同时计数会得到相同的count,生成一样的friendlyId。如果要避免这个问题,可以用mongoose-sequence这类自增插件,或者单独维护一个计数器集合。 - 中间件必须用普通函数,不能用箭头函数,否则无法通过
this访问当前文档实例。
内容的提问来源于stack exchange,提问作者IbrarMumtaz
相关产品推荐
相关产品推荐

