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

Node.js API结合MongoDB聚合查询报错:意外令牌问题求助

Hey there! Let's fix that unexpected token error and get your MongoDB aggregation query working properly with Node.js.

First, the immediate cause of your "unexpected token" error is right in your $match stage: you've got new Date... which is incomplete JavaScript syntax. The JS parser has no idea how to handle those ellipses, so it throws that error immediately. You need to finish that Date constructor call with a valid argument.

Let's walk through fixing and improving your code step by step:

1. Fix the Broken Date Syntax

Replace the truncated new Date... with a complete Date instance. For example, if you want to query records from the past year, your $match stage should look like this:

{ "$match": {
  "CREATE_DATE": {
    "$lte": new Date(), // Current date/time
    "$gte": new Date(Date.now() - 365 * 24 * 60 * 60 * 1000) // 1 year ago (adjust as needed)
  }
}}

Never leave incomplete expressions like new Date... in your code—every constructor call needs to be fully written out.

2. Handle Month Name Mapping Correctly

Your monthsEnum object is defined in Node.js, but MongoDB's aggregation pipeline can't access variables from your Node environment directly. If you want to map numeric months to their names in query results, use MongoDB's native aggregation operators like $switch in a $project stage:

Air_pollution.aggregate([
  // Your fixed $match stage first
  { "$match": { /* ... */ } },
  // Add a $project stage to map month numbers to names
  {
    "$project": {
      "year": { "$year": "$CREATE_DATE" },
      "monthName": {
        "$switch": {
          "branches": [
            { "case": { "$eq": [{ "$month": "$CREATE_DATE" }, 1] }, "then": "January" },
            { "case": { "$eq": [{ "$month": "$CREATE_DATE" }, 2] }, "then": "February" },
            { "case": { "$eq": [{ "$month": "$CREATE_DATE" }, 3] }, "then": "March" },
            // Add cases for months 4-12 here
          ],
          "default": "Unknown Month"
        }
      },
      // Include other fields you need from your documents
      "pollutionLevel": 1,
      "location": 1
    }
  },
  // Add other aggregation stages (like $group) if needed
])

3. Additional Debugging Tips

  • Check for missing commas/brackets: Aggregation pipelines are arrays of objects, so make sure every stage is separated by a comma, and all curly braces/brackets are properly closed.
  • Validate the pipeline with console.log: Print the full aggregation array to your terminal before running it to catch syntax issues early:
    const pipeline = [ /* your full aggregation stages */ ];
    console.log(JSON.stringify(pipeline, null, 2));
    
  • Use Mongoose debug mode: If you're using Mongoose, enable debug logging to see the exact query sent to MongoDB:
    const mongoose = require('mongoose');
    mongoose.set('debug', true);
    
  • Handle errors properly: Make sure you're catching errors from the aggregation call. Prefer async/await for modern Node.js:
    app.get('/polute', async function (req, res) {
      try {
        const pipeline = [ /* your fixed stages */ ];
        const results = await Air_pollution.aggregate(pipeline);
        res.json(results);
      } catch (err) {
        console.error('Aggregation error:', err);
        res.status(500).send(err.message);
      }
    });
    

Once you fix the incomplete new Date call and ensure your pipeline syntax is valid, that unexpected token error should disappear. Then you can tweak the aggregation stages to get your desired results.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:53:47