I have the following document:
{
_id: asdfasdf,
title: "ParentA",
children: [
{
_id: abcd <-- using new ObjectId() to generate these on creation
title: "ChildA",
},
{
_id: efgh,
title: "ChildB"
}
]
}
What I want to do is use findOne but I only want the returned document to contain a single child in its array.
Sudo logic
Categories.findOne({ _id: "asdfasdf" }, { children: _Id: "abcd" });
I want the returned document to look like this:
{
_id: asdfasdf,
title: "ParentA",
children: [
{
_id: abcd <-- using new ObjectId() to generate these on creation
title: "ChildA",
}
]
}
The purpose of this is so I can pass the information into an edit form, and then update that single child object in the array on save.
I'm getting confused as to how to limit the result set.
Thank you very much!
---- Edit ----
After attempting to use the suggested duplicate question as a reference, I'm getting undefined in my results. I really want to use findOne instead of find() as well. On the client, a collection object, even though it contains one item, is treated differently than a single (findOne) object that is returned.
Here is what I've tried.
db.Category.findOne({
"_id": parentid,
"children._id": childid
},{
"_id": childid,
"children": {
"$elemMatch": {
"_id": childid
}
}
});
db.Category.findOne({
"_id": parentid
},{
"children": {
"$elemMatch": {
"_id": childid
}
}
});
I've tried several more variations like the above.
---- Edit 2 ----
Based on a comment, here is the output of the following query:
db.category.findOne({ "_id" : "9dYgKFczgiRcNouij"});
{
"title" : "Appliances",
"active" : true,
"children" : [
{
"_id" : ObjectId("680d55c6995ef6f0748278c2"),
"title" : "Laundry",
"active" : true
},
{
"_id" : ObjectId("2b4469c1a4c8e086942a1233"),
"title" : "Kitchen"
"active" : true
},
{
"_id" : ObjectId("4f5562ef7668839704c851d6"),
"title" : "Other"
"active" : true
}
],
"_id" : "9dYgKFczgiRcNouij"
}
So I think perhaps my problem is how I created the children._id in the array. I used new ObjectId() to generate the _id.
--- Edit 3 ---
db.category.findOne({
"_id": "9dYgKFczgiRcNouij"
},{
"children": {
"$elemMatch": {
"_id": ObjectId("4f5562ef7668839704c851d6")
}
}
});
This returns ObjectID is not defined.