我想制作 searchDate API(我正在使用 Express、Mongoose 和 Angular)。我需要回傳兩個日期之間的資料串列。
不知何故,只有當我在 $gte 和 $lt 中硬編碼日期時它才有效
我的api代碼:
router.get("/searchDate", async (req, res) => {
try {
const { startDate, endDate } = req.query;
const containers = await Container.aggregate([
{
$match: {
$or: [
{
manufacturingDate: {
$gte: new Date(startDate),
$lt: new Date(endDate),
},
},
],
},
},
]);
res.status(200).json(containers);
} catch (err) {
res.status(404).json({ success: false, msg: "Container not found" });
}
});
我的模型是:
import * as mongoose from "mongoose";
const ContainerType = require("./ContainerType");
const Schema = mongoose.Schema;
const ContainerSchema = new mongoose.Schema({
owner: { type: String, required: true },
manufacturingNo: { type: String, required: true },
IdentificationNo: { type: String, required: true },
manufacturingDate: { type: Date, required: true },
nextInspectionDate: { type: Date, required: true },
});
module.exports = mongoose.model("Containers", ContainerSchema);
這就是我的 MongoDB Compass 中日期的樣子

我從 api /searchDate 得到的錯誤是:

uj5u.com熱心網友回復:
這實際上與 Mongo 無關,只是一個常規的 TypeScript 錯誤。
和變數startDate(endDate據 TS 所知)不一定可以安全地構造 Date 物件。
你可以投,前new Date(String(startDate)),或更好,assert或throw以上的某個地方 if typeof startDate !== 'string'。
這是假設這startDate確實是一個字串,這很有可能但不一定是真的(正如 TypeScript 告訴你的那樣)。
請記住,從字串構造 Date 也可能會生成Invalid Date物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/490192.html
上一篇:如何在反應中連接mongoDB
下一篇:為查詢引數化分頁
