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

部署到Heroku后出现Mongoose-Encryption配置错误求助

问题解决:Heroku部署后mongoose-encrypt密钥缺失导致崩溃

核心原因

本地运行时.env文件能正常加载环境变量,但部署到Heroku时,.env文件被gitignore排除,没有推送到Heroku服务器,导致process.env.SOME_LONG_UNGUESSABLE_STRING取不到值,触发插件的密钥验证错误。

解决步骤

  1. 在Heroku配置环境变量
    登录Heroku控制台,找到你的应用,进入「Settings」标签页,在「Config Vars」区域添加键值对:

    • 键:SOME_LONG_UNGUESSABLE_STRING
    • 值:Thisisa32bytebasestring(和你本地.env里的内容一致)
  2. 修正代码细节

    • 补上mongoose-encryption插件的引入代码,否则会找不到encrypt对象
    • 修正加密字段名:Schema里定义的是小写password,代码里写的大写Password会导致加密失效,改成一致的小写

修正后的server.js关键代码:

require('dotenv').config();
const mongoose = require("mongoose");
const encrypt = require('mongoose-encryption'); // 补上插件引入

const tytyDigitalSchema = new mongoose.Schema({
  username: String,
  password: String,
  email: String,
  verified: Boolean
});

var secret = process.env.SOME_LONG_UNGUESSABLE_STRING;
tytyDigitalSchema.plugin(encrypt, { secret: secret, encryptedFields: ['password'] }); // 修正字段名

const Users = mongoose.model("user", tytyDigitalSchema);
  1. 重新部署代码
    提交代码到Git后推送到Heroku:
    git add .
    git commit -m "修复加密配置问题"
    git push heroku main
    

额外验证

部署后可以通过Heroku命令行确认环境变量是否生效:

heroku config:get SOME_LONG_UNGUESSABLE_STRING

如果返回你设置的密钥值,说明配置正确。

内容的提问来源于stack exchange,提问作者James Driscoll

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:24:48