Arrays 将数组从React客户端传递到MongoDB
我在服务器端有一个get路由,它使用来自MongoDB的两条随机记录进行响应。我目前有一对记录作为排除记录硬连线,永远不会返回到客户端Arrays 将数组从React客户端传递到MongoDB,arrays,node.js,mongodb,reactjs,Arrays,Node.js,Mongodb,Reactjs,我在服务器端有一个get路由,它使用来自MongoDB的两条随机记录进行响应。我目前有一对记录作为排除记录硬连线,永远不会返回到客户端 app.get("/api/matchups/:excludedrecords", (req, res) => { const ObjectId = mongoose.Types.ObjectId; Restaurant.aggregate([ { $match: { _id: { $nin: [ObjectId
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。我希望用户能够从随机查询中排除多条记录。我有一个action creator,它通过一个reducer推送用户希望排除的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}')
,这会导致我传递一个看起来像我想要的数组,但当它被字符串化并解析后,就不太管用了
如果这个问题有点混乱,很抱歉。首先,您应该将字符串数组作为http请求的主体传递,而不是作为url的一部分传递。不能将数组参数作为url的一部分或在查询字符串中传递 其次,必须将代码转换为$nin:[ObjectId(excludedRecord1)、ObjectId(excludedRecord2)] 在服务器端 希望有帮助