Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

85
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda