Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

84
Views
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 responds 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".

Thanks for helping!

The error message:

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

In the model I do not have to be unique the id.

Order 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

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
  }}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The "index: userId_1" in the error message indicates that there is an index on the "userId" field in the database.

Drop the index and this shouldn't happen anymore.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!