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

340
Vistas
Express mongoose populate array of subdocuments from POST

This is my Mongoose Schema:

const InvoiceSchema = new Schema({
name: { type: String, required: true },
description: { type: String },

items: [{
    product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product'},
    amount: { type: Number },
    name: { type: String, required: true },
    quantity: { type: Number },
    rate: { type: Number, required: true }
}],
createdBy: { type: Schema.ObjectId, ref: 'User', required: true },
}

Now I want to populate my Schema from POST Datas, My problem is I don't Know how to post my items (How do I name my fields)??

I use PostMan to post Datas.

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

To get post data

To add a new record in mongoose

const {ObjectId} = mongoose.Schema.Types;
const newInvoice = new InvoiceSchema({
  name: "John Smith",
  description: "This is a description",
  items: [{
    product: 'THIS_IS_AN_OBJECT_ID_STRINGIFIED',
    amount: 2,
    quantity: 5,
    //name - comes from the product model
    //rate - comes from the product model
  }]
});

newInvoice.save();

To POST and save it

//Response format
{
  name: 'John Smith',
  description: 'This is a description',
  items: [
    {
      product: 'THIS_IS_AN_OBJECT_ID',
      amount: 2,
      quantity: 5
    }
  ]
}

app.post('/yourRoute', (req, res) => {
  const {name, description, items} = req.body;
  const newInvoice = new InvoiceSchema({name, description, items});
  newInvoice.save().then(()=>res.send('success'))
});
about 4 years ago · Santiago Trujillo Denunciar

0

To bulk add items

const invoice = new Invoice();
invoice.items = req.body.items;

To add single item

invoice.items.push(item);

To update single item

const item = invoice.items.id(req.params._id);
item.attribute = ...
// Do update
about 4 years ago · Santiago Trujillo 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