我试图使用URL中包含的参数过滤存储在MongoDB中的一些数据.
我的问题是,当发送请求时,服务器崩溃,并显示以下错误:
can't convert from BSON type string to Date
个
我try 将变量类型更改为Number
,希望它能解决问题,但结果相同.
下面是我用来向服务器发送请求的代码:
async filter(){
month = this.$refs.month.value;
year = this.$refs.year.value;
if(month != "Month" && year != ""){
const addressToFetch = "/api/budget/" + year + "/" + month;
console.log("Fetching" + addressToFetch);
await fetch(addressToFetch).then(response => response.json())
.then(response => {
this.expenses = response;
console.log(response);
});
}
}
此函数在单击一个HTML表单按钮时执行,并从两个表单输入中获取值.
下面是我用来处理服务器端请求的代码:
app.get("/api/budget/:year/:month", verify, async (req, res) => {
const user = req.session.user;
const year = Number(req.params.year);
const month = Number(req.params.month);
console.log("Got " + year + "/" + month);
const expenses = db
.collection("expenses")
.find({
"users.username": user.username,
$expr: {
$and: [
{ $eq: [{ $year: "$date" }, year] },
{ $eq: [{ $month: "$date" }, month] },
],
},
})
.toArray();
console.log(expenses);
res.json(expenses);
});
出于演示目的,我还发布了存储在数据库中的文档:
[
{
"_id": "6571eb70320499f416931fd8",
"id": 2,
"date": "2021-09-06T00:00:00.000Z",
"description": "boringday",
"category": "transport",
"buyer": "giacomo",
"cost": 49,
"users": [
{
"username": "paolo",
"amount": 16.333333333333332
},
{
"username": "giacomo",
"amount": 16.333333333333332
},
{
"username": "giacomo",
"amount": 16.333333333333332
}
]
},
{
"_id": "6571eb70320499f416931fe8",
"id": 18,
"date": "2019-04-10T00:00:00.000Z",
"description": "badday",
"category": "school",
"buyer": "giacomo",
"cost": 329,
"users": [
{
"username": "luca",
"amount": 109.66666666666667
},
{
"username": "luca",
"amount": 109.66666666666667
},
{
"username": "giacomo",
"amount": 109.66666666666667
}
]
},
{
"_id": "6571eb70320499f416931feb",
"id": 21,
"date": "2021-11-14T00:00:00.000Z",
"description": "boringexperience",
"category": "school",
"buyer": "giacomo",
"cost": 299,
"users": [
{
"username": "giorgia",
"amount": 99.66666666666667
},
{
"username": "giacomo",
"amount": 99.66666666666667
},
{
"username": "giacomo",
"amount": 99.66666666666667
}
]
},
{
"_id": "6571eb70320499f416931fff",
"id": 41,
"date": "2020-04-09T00:00:00.000Z",
"description": "badtool",
"category": "sport",
"buyer": "giacomo",
"cost": 349,
"users": [
{
"username": "franco",
"amount": 116.33333333333333
},
{
"username": "franco",
"amount": 116.33333333333333
},
{
"username": "giacomo",
"amount": 116.33333333333333
}
]
}
]
例如,在提交表单时,值为year=2021, month=11
,我只希望返回第三个对象.
有人能帮我解决这个问题吗?
提前感谢您的耐心等待!