[英]Error in my backend when I'm trying to send an array of ObjectID from a post router from my frontend (React-Native/Mongoose)
It's only been a few months that I've begun coding.我才开始编码才几个月。 I'm currently working on a project to create an application for shopping on React-Native with Mongoose as my database.
我目前正在开发一个项目,创建一个在 React-Native 购物的应用程序,并将 Mongoose 作为我的数据库。 I'm trying to post in my database my customer's order but my terminal crash because it doesn't recognize my array of articles.
我试图在我的数据库中发布我的客户订单,但我的终端崩溃了,因为它无法识别我的文章数组。
My order model is:我的订单model是:
const mongoose = require("mongoose");
var orderSchema = mongoose.Schema({
OrderNumber: String,
totalOrder: Number,
shippingCost: Number,
date_insert: Date,
date_shipment: Date,
articles: [{ type: mongoose.Schema.Types.ObjectId, ref: "articles" }],
});
var OrderModel = mongoose.model("orders", orderSchema);
module.exports = OrderModel;
my index.js:我的索引.js:
router.post("/orders", async function (req, res, next) {
var result = false;
var response = false;
var orderNumber = Math.floor(Math.random() * Math.floor(1000000) + 1);
var shippingCost = 5;
var user = await UserModel.findOne({ token: req.body.token });
if (user != null) {
var newOrder = new OrderModel({
OrderNumber: orderNumber,
totalOrder: req.body.totalOrder,
shippingCost: shippingCost,
date_insert: req.body.date_insert,
date_shipment: req.body.date_shipment,
articles: req.body.articles,
locker: req.body.locker,
});
var orderSave = await newOrder.save();
if (orderSave) {
result = true;
}
if (result) {
user.orders.push(orderSave._id);
response = true;
await user.save();
res.json({ user, response });
} else {
res.json(err.message);
}
} else {
res.json("Something went wrong");
}
});
In my frontend在我的前端
My article basket is store in a reducer saveBasket我的文章篮存储在 reducer saveBasket 中
var tab = [];
var idList = props.saveBasket.map((article, i) => {
tab = [...tab, article._id];
});
var handleSubmitOrder = async () => {
const data = await fetch("https://heroku.project.com/orders", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: `totalOrder=${props.saveValidateCart}&date_insert=${currentDate}&date_shipment=${deliveryDate}&articles=${tab}&locker=${props.saveIdLocker._id}&token=${props.saveToken}`,
});
const body = await data.json();
};
The error show on my terminal is:我的终端上显示的错误是:
/Users/Documents/BackEnde/node_modules/mongoose/lib/query.js:4650
const castError = new CastError();
^
CastError: Cast to ObjectId failed for value "621cb042067e1819e87f7ee8,621cb2b4067e1819e87f7eef" (type string) at path "_id" for model "articles"
at model.Query.exec
(/Users/Documents/BackEnd/node_modules/mongoose/lib/query.js:4650:21)
at model.Query.Query.then
(/Users/Documents//BackEnd/node_modules/mongoose/lib/query.js:4749:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
messageFormat: undefined,
stringValue: '"621cb042067e1819e87f7ee8,621cb2b4067e1819e87f7eef"',
kind: 'ObjectId',
value: '621cb042067e1819e87f7ee8,621cb2b4067e1819e87f7eef',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters
at new BSONTypeError (/Users/Documents/fraiche/BackEnd/node_modules/bson/lib/error.js:41:28)
at new ObjectId
(/Users/Documents/BackEnd/node_modules/bson/lib/objectid.js:65:23)
at castObjectId
(/Users/Documents/BackEnd/node_modules/mongoose/lib/cast/objectid.js:24:12)
at ObjectId.cast
(/Users/Documents/BackEnd/node_modules/mongoose/lib/schema/objectid.js:247:12)
at ObjectId.SchemaType.applySetters
(/Users/Documents/BackEnd/node_modules/mongoose/lib/schematype.js:1179:12)
at ObjectId.SchemaType._castForQuery
(/Users//Documents/BackEnd/node_modules/mongoose/lib/schematype.js:1613:15)
at ObjectId.SchemaType.castForQuery
(/Users/Documents/BackEnd/node_modules/mongoose/lib/schematype.js:1603:15)
at ObjectId.SchemaType.castForQueryWrapper
(/Users//Documents/BackEnd/node_modules/mongoose/lib/schematype.js:1580:20)
at cast (/Users//Documents/BackEnd/node_modules/mongoose/lib/cast.js:344:32)
at model.Query.Query.cast
(/Users/Documents/BackEnd/node_modules/mongoose/lib/query.js:5085:12),
valueType: 'string'
I don't understand because when I console.log tab in my front end, an array with my articles id is shown but when send on my backend it ends up being a string?!
Can someone help me understand what is wrong?有人可以帮我理解哪里出了问题吗? Thank you and sorry for any grammatical mistake, English isn't my native language
谢谢您,对于任何语法错误,我深表歉意,英语不是我的母语
You are sending 2 IDs to the server as a String
, they need to be properly parsed.您正在将 2 个 ID 作为
String
发送到服务器,它们需要被正确解析。 If IDs are articles try doing this in the backend, where you're constructing your order如果 ID 是文章,请尝试在构建订单的后端执行此操作
var newOrder = new OrderModel({
OrderNumber: orderNumber,
totalOrder: req.body.totalOrder,
shippingCost: shippingCost,
date_insert: req.body.date_insert,
date_shipment: req.body.date_shipment,
articles: req.body.articles.split(",").map(article => ObjectId(article)),
locker: req.body.locker,
});
This is your issue here:这是你的问题:
body: `totalOrder=${props.saveValidateCart}&date_insert=${currentDate}&date_shipment=${deliveryDate}&articles=${tab}&locker=${props.saveIdLocker._id}&token=${props.saveToken}`,
Your node
app is looking for a JSON object in the post request and you're passing in a single string
of url parameters.您的
node
应用程序正在 post 请求中查找 JSON object,并且您正在传递一个包含 url 参数的string
。
Try this.尝试这个。 I don't know how your
props
is structured but this should get you close.我不知道你的
props
是如何构建的,但这应该让你接近。
const url = "https://heroku.project.com/orders";
const body = {
totalOrder: props.saveValidateCart,
date_insert: currentDate,
date_shipment: deliveryDate,
articles: tab,
locker: props.saveIdLocker._id,
token: props.saveToken
};
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: JSON.stringify(body)
};
const response = await fetch(url, requestOptions);
const data = await response.json();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.