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

476
Views
Mongoose auto increment a subdocuments field in array

I'm pushing subdocuments to an array:

const deliverySchema = new db.Schema({
  deliveryId: Number,
  amountDelivered: Number,
  price: Number
})

const suppliersSchema = new db.Schema({
  supplierName: String,
  phone:  Number,
  deliveries: [deliverySchema]
})

const delivery =  {
  "amountDelivered": 123,
  "price": 123
}

Suppliers.updateOne(
  { _id: supplierId },
  { $push: { deliveries: delivery } }
)

How can I have the deliveryId field inside that document auto increment on update. So the result would look something like:

{
  "supplierName": "Test supplier",
  "phone": 12345678,
  "deliveries": [
    {
      "deliveryId": 1, // Auto increment this field on update
      "amountDelivered": 123,
      "price": 123
    },
    {
      "deliverId": 2,
      "amountDelivered": 123,
      "price": 1234
    }
  ]
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do it with Aggregation Framework:

  • $concatArrays - to concatenate the current deliveries array with new item
  • $size - to get the current size of the deliveries array
  • $sum - to sum current size of the deliveries array with 1 and use the result to set deliveryId
db.collection.update({
  "key": 1
},
[
  {
    "$set": {
      "deliveries": {
        "$concatArrays": [
          "$deliveries",
          [
            {
              "deliveryId": {
                "$sum": [
                  1,
                  {
                    "$size": "$deliveries"
                  }
                ]
              },
              "amountDelivered": 123,
              "price": 123
            }
          ]
        ]
      }
    }
  }
])

Working example

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!