简体   繁体   English

当我尝试从我的前端(React-Native/Mongoose)的后路由器发送一组 ObjectID 时,我的后端出错

[英]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.

相关问题 未从 Flask 后端接收 React-Native 前端 - Not receiving on React-Native frontend from Flask backend 我在 React-Native 中从 Firebase 渲染我的数据时遇到问题 - I'm having trouble rendering my data from Firebase in React-Native 在handleSubmit函数中向后端发出Post请求时,我试图阻止浏览器刷新 - I am trying to stop my browser from refreshing when making a Post request to the backend in my handleSubmit function JSON 解析错误:尝试解析数组中的对象时出现意外的标识符“未定义”(React-Native) - JSON Parse error: Unexpected identifier "undefined" when trying to parse an object from an array (React-Native) 我在 Android 上的 React Native 应用程序中尝试对用户进行身份验证时收到来自服务器的 401 错误 - I receive a 401 error from the server when trying to authenticate a user in my React Native app on Android 尝试从后端向前端发送 zip - Trying to send a zip from the backend to the frontend 我可以在前端使用后端的OAuth令牌吗? - Can I use an OAuth token from backend in my frontend? 在Macbook上运行react-native项目时出现路径错误 - Path error when running react-native project on my macbook 将react-native侧面菜单添加到我的应用程序(通过react-native元素)-应用程序在启动时崩溃 - Adding react-native side menu to my application (from react-native elements) - application crashes on launching Flatlist React-Native 组件阻止我的数组填充导致应用程序崩溃 - Flatlist React-Native component prevents my array from populating causing app to crash
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM