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

155
Views
How to $push: into mongo-db after incrementing id using $inc

I need to to increment the value of the ID before inserting into the Mongodb. I tried $inc but it ain't working . Here is my Mongoose Schema

const subSchema = new mongoose.Schema({
    id:{
        type:Number,
        default:1

    },
    time : { type : Date, default: Date.now },
    description:{
        type:String,
        required:true
    }
})
const activitySchema = new mongoose.Schema({
    userid:{
        type:String,
        required:true
    },
    activity:[subSchema]
})

I am trying to update id in subSchema which is later used in activitySchema

This is what id did initially.

findOneAndUpdate({userid:userid}, { $push: { activity: {description:"Test",$inc:{ id: 1} } } })

Document is getting inserted but with default value as 1 for all
When i removed default:1 from id, The document is getting updated without id
Any easy solution for this ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Its impossible to be done in one query. Instead you can do it in 2 steps as:

const user = await Activity.findOne({ userid });
//                  ^^^^^ put your collection name here
if (user) {
    const activityCount = user.activity.length;

    await user.updateOne({ $push: { activity:
        { id: activityCount + 1, description: 'Dolor sit amet' }
    }})
}
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!