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

252
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

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'))
});
over 4 years ago · Santiago Trujillo Report

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
over 4 years ago · Santiago Trujillo 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!