Home > other >  How to get a subarray of a document with mongoose
How to get a subarray of a document with mongoose

Time:04-09

I have this document Schema:

    {
    "success": true,
    "data": {
        "_id": "624c0ac20f0df948f8bf8cf1",
        "collection_name": "pog7",
        "by": "soeww",
        "private": "$2a$10$U3dRJxUQLm9GvuS5g3qkF.fMVJCdxrLAarFiGQ900EarayWBvrZya",
        "fens": [
            {
                "fen": "pog",
                "san": "d4",
                "_id": "624c0ac20f0df948f8bf8cf2"
            }
        ],
        "__v": 0
    }
}

is there a function in mongoose to target the "_id" field of an array inside a document? It would be very convenient to use like Schema.findById() to get the single element. I have tried to use findById but it returns null.

CodePudding user response:

The right way is:

db.collection.find({fens: {$elemMatch: {_id: "624c0ac20f0df948f8bf8cf2" }}})

$elemMatch allows you to match more than one component within the same array element.

You can run it here to check the same query https://mongoplayground.net/p/HsVvy3Vjb-d

You can also have a look at documentation of $elemMatch in this link.

Let me know if you face any issue.

CodePudding user response:

elemMatch() function is used to specify the $elemMatch condition, for people using mongoose.

await User.find().elemMatch("fens", {"_id":"624c0ac20f0df948f8bf8cf2"});
  • Related