简体   繁体   English

Redux 和 MongoDB 不创建新文档

[英]Redux and MongoDB dont create a new Document

I have a problem when I create the first order.创建第一个订单时遇到问题。 I can´t make a new order after that.之后我不能再下新订单了。 The server response with a 404 ":5006/api/orders:1 Failed to load resource: the server responded with a status of 404 (Not Found) apiRequests.js?t=1641540961019:30 Request failed with status code 404".服务器响应为 404“:5006/api/orders:1 加载资源失败:服务器响应状态为 404(未找到)apiRequests.js?t=1641540961019:30 请求失败,状态码为 404”。 Thanks for helping!感谢您的帮助!

The error message: { "error": true, "message": "E11000 duplicate key error collection: MERN-AMAZON.orders index: userId_1 dup key: { userId: "61cd3c5d004cba23aa81a85b" }" }错误消息:{“error”:true,“message”:“E11000重复密钥错误集合:MERN-AMAZON.orders索引:userId_1 dup key:{userId:“61cd3c5d004cba23aa81a85b”}”}

In the model I do not have to be unique the id.在 model 中,我不必是唯一的 id。

Order Model订购 Model

const OrderSchema = new Schema({
userId:{
    type:String,
    required:true
},
products:[
    {
        productId:{
            type:String,
        },
        title:{
            type:String
        },
        image:{
            type:String
        },
        price:{
            type:Number
        },
        quantity:{
            type:Number,
            default:1
        },
        _id:false
    }
],
amount:{
    type:Number,
    required:true
}
},{timestamps:true})

Confirm Order确认订单

useEffect(() => {
if(searchParams.get("status") === "approved" && user){ //Payment service has an autoreturn and modify the url with a query when the payment is approved. Example: /orders/?approved=true



  setSearchParams("") //Delete query because make a emptys orders in my DB
  addOrders({ userId:user.user._id,products:cart.products,amount:cart.total},user.token,dispatch)//POST the new order
  dispatch(emptyCart()) //Empty my shop-cart
}
  }, [])

Create Order Controller创建订单 Controller

exports.createOrder = async (req,res)=>{
let order = req.body
let modifyProducts = order.products.map(elem => {
    return {productId:elem._id,quantity:elem.quantity,title:elem.title,image:elem.image,price:elem.price}
    }
    )
console.log(modifyProducts)
const newOrder = new Order({userId:order.userId,products:modifyProducts, amount:order.amount })
try {
    const createOrder = await newOrder.save()
    res.status(200).json(createOrder)
} catch (error) {
    res.status(404).json({error:true,message:error.message})
}}

addOrder Dispatch添加订单调度

    export const addOrders = async (order,token,dispatch)=>{ //Tengo que sacar el query que me devuelve ML porque me crea orders
  try{
    let newOrder = await axios({
      method:"POST",
      url:"http://localhost:5006/api/orders",
      data:order,
      headers:{
        Authorization: `Bearer ${token || " "}`
      }
    })
    console.log(newOrder)
    dispatch(ordersAdd(newOrder.data))
  }catch(err){
    console.log(err.message) //This error appears on console
  }}

The "index: userId_1" in the error message indicates that there is an index on the "userId" field in the database.错误信息中的“index:userId_1”表示数据库中的“userId”字段存在索引。

Drop the index and this shouldn't happen anymore.删除索引,这不应该再发生了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM