Home > Net >  Update object in array if Object Exist else create new one in mongoose
Update object in array if Object Exist else create new one in mongoose

Time:11-21

This is Streak Collection and I want to search today date in streaks array if it exists then simply update the question count else create a new Object with the today date.

_id : {
    type: mongoose.Types.ObjectId,
    ref: "User",
},
streaks :[{
    date :{
        type : Date,
        required : true
    },
    questionCount :{
        type : Number,
        required : true,
        default : 0
    }
}]

CodePudding user response:

Query

  • check if day of $$NOW date is new
  • if new $concatArrays to add the new date with counter=1
  • else $map to update just the counter of the found date

*$$NOW is a system variable that has the current date, if you don't want the current date you can put any date you like in "$$NOW" place

*$dateTrunc with unit=day keeps from the date only the part before day (ignores time)

Examples are made for 20 November 2021 (change the data if you test them later)
Test code here(today exists)
Test code here(today doesn't exists)

update(
{"_id": {"$eq": 1}},
[{"$set": 
    {"new": 
      {"$eq": 
        [{"$filter": 
            {"input": "$streaks",
              "cond": 
              {"$eq": 
                [{"$dateTrunc": {"date": "$$NOW", "unit": "day"}},
                  {"$dateTrunc": {"date": "$$this.date", "unit": "day"}}]}}},
          []]}}},
  {"$set": 
    {"streaks": 
      {"$cond": 
        ["$new",
          {"$concatArrays": 
            ["$streaks", [{"date": "$$NOW", "questionCount": 1}]]},
          {"$map": 
            {"input": "$streaks",
              "in": 
              {"$cond": 
                [{"$eq": 
                    [{"$dateTrunc": {"date": "$$NOW", "unit": "day"}},
                      {"$dateTrunc": {"date": "$$this.date", "unit": "day"}}]},
                  {"$mergeObjects": 
                    ["$$this",
                      {"questionCount": {"$add": ["$$this.questionCount", 1]}}]},
                  "$$this"]}}}]}}}])
  • Related