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

156
Views
Cómo $empujar: en mongo-db después de incrementar la identificación usando $inc

Necesito incrementar el valor de la ID antes de insertarla en Mongodb. Intenté $inc pero no funciona. Aquí está mi esquema de mangosta

 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] })

Estoy tratando de actualizar la identificación en subSchema que luego se usa en activitySchema

Esto es lo que hizo id inicialmente.

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

El documento se está insertando pero con un valor predeterminado de 1 para todos
Cuando eliminé el valor predeterminado: 1 de la identificación, el documento se actualiza sin identificación
¿Alguna solución fácil para esto?

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

0

Es imposible hacerlo en una sola consulta. En su lugar, puede hacerlo en 2 pasos como:

 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!