【问题标题】:Redux and MongoDB dont create a new DocumentRedux 和 MongoDB 不创建新文档
【发布时间】:2022-01-07 08:44:21
【问题描述】:

我在创建第一个订单时遇到问题。之后我不能再下新订单了。 服务器以 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".

感谢您的帮助!

错误信息:

{
    "error": true,
    "message": "E11000 duplicate key error collection: MERN-AMAZON.orders index: userId_1 dup key: { userId: \"61cd3c5d004cba23aa81a85b\" }"
}

在模型中我不必是唯一的 id。

订单模式

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})

确认订单

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
}
  }, [])

创建订单控制器

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})
}}

添加订单调度

    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
  }}

【问题讨论】:

  • 检查您的服务器端代码。某些原因导致它崩溃,因此出现404: Not Found 错误。
  • 错误就像我在 userId 字段上有一个唯一的。如果我放一个console.log(newOrder)。它不显示顺序。

标签: javascript node.js reactjs mongodb redux


【解决方案1】:

错误信息中的“index:userId_1”表示数据库中的“userId”字段存在索引。

删除索引,这不应该再发生了。

【讨论】:

  • 如果我在 userId 字段上放了一个独特的选项是有意义的
猜你喜欢
  • 2016-11-11
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
相关资源
最近更新 更多