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 ?
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' }
}})
}