You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose Schema中定义默认函数?解决Promise pending报错

解决方案

Mongoose的字段default选项不支持异步函数返回Promise,它会直接把Promise对象当作字段值,这就是你看到"Promise { }"无法转成数字的原因。

要实现save()时自动计算填充friendlyId,别用default,改用Mongoose的pre-save中间件,步骤如下:

  1. 先调整字段定义,去掉default和强制required(中间件会自动填充,不需要用户传入):
friendlyId: {
    type: Number,
    unique: true,
    index: true
}
  1. 给模型添加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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:25:23