Mongoose Nodejs pull element from array by property of property

So here is my mongoose Object:

	{
		"username" : "Raxo",
		"score" : 0,
		"solved" : [
			{
				"challenge" : {
					"_id" : ObjectId("62716b84cef98df9866d6a8a"),
					"name" : "Challenge1884  ",
					"category" : "crypto",
					"flag" : "Nice try XD",
					"hints" : [
						"Easy Peasy Lemon Squeezy!"
					],
					"points" : 100,
					"info" : "I am a challenge!",
					"level" : 0,
					"solveCount" : 1,
					"file" : "",
					"__v" : 0
				},
				"timestamp" : 1651602135100
			}
		]
}

I am trying to delete the challenge inside the solved array using:

        await users.updateMany({
            solved: { $elemMatch: { 'challenge._id': challengeExists._id } }
        }, {
            $inc: { score: -challengeExists.points },
            $pull: { solved: { $elemMatch: { 'challenge._id': challengeExists._id } } }
        });
type or paste code here

It does find the user successfully and remove points from the score but does not successfully pull the challenge, I cant seem to find what I am doing wrong. Any help appreciated

Hi @Oscar_Gomez - Welcome to the community! :wave:

Could you provide more details about your use case and expected output? I would just like to clarify as I imagine there may be a case where there are multiple challenges in the solved array field.

In saying so, could you please also provide the following information as well:

  • MongoDB version in use
  • Mongoose version in use
  • Mongoose schema associated with this sample document provided
  • Multiple sample input documents (Perhaps some sample documents with multiple challenges inside the solved array field)
  • The expected output

Regards,
Jason

2 Likes