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. 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 :
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:
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
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
CodePudding user response:
You are sending 2 IDs to the server as a String
, they need to be properly parsed. If IDs are articles try doing this in the backend, where you're constructing your order
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,
});
CodePudding user response:
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 .
Try this. I don't know how your props
is structured but this should get you close.
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();