我在服务器端有一条get路由,它响应来自MongoDB的两条随机记录。我目前有几条记录以硬连线方式作为排除记录,这些记录将永远不会返回给客户。
app.get("/api/matchups/:excludedrecords", (req, res) => {
const ObjectId = mongoose.Types.ObjectId;
Restaurant.aggregate([
{
$match: {
_id: { $nin: [ObjectId("5b6b5188ed2749054c277f95"), ObjectId("50mb5fie7v2749054c277f36")] }
}
},
{ $sample: { size: 2 } }
]).
这有效,但是我不想硬连接排除的记录,我想从客户端动态传递ObjectId。我希望用户能够从随机查询中排除多个记录。我有一个动作创建者,它通过缩减程序将用户希望排除的ObjectId推入,使其成为存储的一部分,而存储是一个数组,其中包含用户希望排除的记录的所有ObjectId。这是我获取随机记录的操作,将存储中的排除记录作为参数:
export function fetchRecords(excludedrecords) {
const excludedarray = JSON.stringify(excludedrecords); // Don't currently have this, but feel like I need to.
const request =
axios.get(`http://localhost:3000/api/matchups/${excludedarray}`);
return {
type: "FETCH_MATCHUP_DATA",
payload: request
};
}
我认为我需要在客户端对数组进行字符串化处理,然后在服务器端对其进行解析,但是我不确定如何做。我开始像这样:
app.get("/api/matchups/:excludedrecords", (req, res) => {
const excludedRecords = JSON.parse(req.params.excludedrecords);
const ObjectId = mongoose.Types.ObjectId;
Restaurant.aggregate([
{
$match: {
_id: { $nin: [excludedRecords] } //
}
},
但是如何获取ObjectId()来包装在参数中传递的每个记录号呢?我尝试将客户端的数字插入模板字符串中,例如ObjectId('${excludedrecord}')
,这导致我传递了一个看起来像我想要的数组,但是当它被字符串化和解析时,它并不能正常工作
抱歉,这个问题有点混乱。
答案 0 :(得分:0)
首先,您应该将字符串数组作为http请求的主体而不是url的一部分传递。您不会在URL或查询字符串中传递数组参数。
第二,必须将代码转码为$ nin:[ObjectId(excludedRecord1),ObjectId(excludedRecord2)]
在服务器端。
希望有帮助!