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

Node.js通过pubdate查询MongoDB无结果,Postman传参求助

通过pubdate字段从MongoDB获取数据无返回也无报错的问题排查与解决

我尝试通过pubdate字段从MongoDB中获取数据,但既无返回数据也无报错。

我的集合包含字段:_id(ObjectId类型)、article、headline、pubdate(其余均为String类型)。

在Mongo查询工具(如Compass和Studio 3T)中执行以下查询可正常得到数据:

{ pubdate: { '$gte': '2022-12-01', '$lte': '2022-12-31' } }

我使用Postman通过Raw选项发送POST请求,JSON参数为:

{"fdate":"2022-12-31","tdate":"2022-12-31"}

我的Node.js代码如下:

const express = require("express");
const app = express();
const port = 3005;
const mongoose = require("mongoose");

// Connect to MongoDB using Mongoose
const url =
  "mongodb://localhost:2701/db";
mongoose.connect(url, { useUnifiedTopology: true, useNewUrlParser: true });
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));

// Define the Article schema
const articleSchema = new mongoose.Schema({
  headline: String,
  fulltext: String,
  pubdate: String,
  article_type: String,
});
const Article = mongoose.model("collectioname", articleSchema);

// Route for retrieving articles based on fromdate and todate
app.post("/articles2", (req, res) => {
  let _fDate = req.body.fdate;
  let _tDate = req.body.tdate;

  Article.find({
    pubdate: { $gte: _fDate, $lte: _tDate },
    
  }).exec((err, articles) => {
    if (err) {
      console.error(err);
      res.status(500).send("Error retrieving articles");
      return;
    }
    res.send(articles);
  });
});

// Start the server
app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

我尝试用map函数处理返回结果也无输出:

let _articles = articles.map((x) => x.articleid); res.send(_articles);

问题排查与解决步骤

1. 缺失JSON请求体解析中间件

Express默认不会自动解析JSON格式的请求体,导致req.body为undefined,查询条件中的_fDate和_tDate无值,自然查不到数据。

解决:在路由定义前添加JSON解析中间件:

app.use(express.json());

2. 集合名称自动转换问题

Mongoose创建模型时,会自动将传入的集合名转为复数形式(比如collectioname会变成collectionames),如果你的实际集合是单数名称,就会查询错误的集合。

解决:定义模型时明确指定实际集合名称:

const Article = mongoose.model("collectioname", articleSchema, "collectioname");

第三个参数为实际集合名,避免Mongoose自动转换。

3. Schema字段与实际集合不匹配

你的Schema中定义了fulltext、article_type,但实际集合字段是article,且没有article_type;后续map中使用的articleid字段也不存在于集合中,这会导致返回文档缺失字段或处理无结果。

解决:修正Schema匹配实际集合字段:

const articleSchema = new mongoose.Schema({
  headline: String,
  article: String, // 替换为实际存在的article字段
  pubdate: String,
});

4. 调试建议

  • 在路由中打印req.body,确认是否正确获取参数:
    console.log("请求参数:", req.body);
    
  • 打印生成的查询条件,对比Mongo工具中的有效查询:
    console.log("查询条件:", { pubdate: { $gte: _fDate, $lte: _tDate } });
    
  • 暂时用硬编码的有效查询条件测试,排查是参数问题还是查询逻辑问题:
    Article.find({ pubdate: { $gte: '2022-12-01', $lte: '2022-12-31' } })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:35:22