Mongoose日期查询在Heroku生产环境异常,本地运行正常求助
Let’s work through the most likely issues causing your query to fail on Heroku, even though it works locally:
1. Fix Critical Variable Name Typos
First, there’s a clear mistake in your date variable setup:
var startDay = new Date(); start.setHours(0, 0, 0, 0); // Uses undefined "start" instead of "startDay" var endDay = new Date(); end.setHours(23, 59, 59, 999); // Uses undefined "end" instead of "endDay"
You declared startDay and endDay, but tried to call setHours() on non-existent variables start and end. This should throw a ReferenceError in strict mode. If this worked locally, it’s likely a copy-paste error in your question, or accidental global variables in your local environment. Correct the code to:
var startDay = new Date(); startDay.setHours(0, 0, 0, 0); // Fixed to use startDay var endDay = new Date(); endDay.setHours(23, 59, 59, 999); // Fixed to use endDay
2. Resolve Timezone Differences (Heroku’s Default is UTC)
Heroku servers run in UTC timezone by default, while your local environment probably uses your local time zone (e.g., UTC+8, UTC-5). When you create dates with new Date(), they reflect the server’s timezone—so your local query targets your local day, but Heroku’s query targets UTC’s day.
To fix this, calculate your date range in UTC for consistent behavior across environments:
const now = new Date(); // Create UTC start/end of current day const startDay = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 0, 0, 0)); const endDay = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 23, 59, 59, 999));
3. Match Mongoose Versions Between Environments
Version mismatches between your local setup and Heroku can cause unexpected behavior. Check your local Mongoose version with npm list mongoose, then update your package.json to specify that exact version (avoid version ranges like ^6.0.0):
"mongoose": "6.12.3" // Replace with your local version
4. Check Heroku Logs for Hidden Errors
Your catch block might not capture all issues. Run heroku logs --tail in your terminal to view real-time production logs. This can reveal connection problems, permission errors, or data formatting issues that aren’t visible in your local console.
5. Verify Production Data Consistency
Ensure your production MongoDB (used by Heroku) has documents matching your query criteria. Sometimes local test data has entries that aren’t present in production, or nextDueDate values are stored as strings instead of Date objects. Use a tool like MongoDB Compass to inspect your production database and confirm data structures match your local setup.
内容的提问来源于stack exchange,提问作者foxenn_pro

