I am currently in the process of creating an e-commerce application with a two-level product type system. For data storage, I have opted to use MongoDB and my chosen programming language is TypeScript.
Here is the model I am using:
class ProductTypeModel {
_id: ObjectID;
name: string;
sort: number; // sort
status: number; // enable | disable
children: Object[]; // sub types, like [{ _id: ObjectID('xx', name: 'xx', sort: xx, status: xx) }]
create_time: Date;
update_time: Date;
}
If we have data like this:
{
"_id" : ObjectId("5b8fe56218de48345a6b7079"),
"create_time" : ISODate("2018-09-05T14:17:06.912Z"),
"update_time" : ISODate("2018-09-05T14:17:06.912Z"),
"name" : "Books",
"sort" : 0,
"status" : 1,
"children" : [
{
"_id" : ObjectId("5b8fe56218de48345a6b7075"),
"name" : "Computer",
"sort" : 1,
"status" : 1
},
{
"_id" : ObjectId("5b8fe56218de48345a6b7076"),
"name" : "Math",
"sort" : 2,
"status" : 0
},
{
"_id" : ObjectId("5b8fe56218de48345a6b7077"),
"name" : "Novel",
"sort" : 3,
"status" : 1
}
]
}
What would be the best way to select all types and child types where status=1
?
At present, my approach involves selecting main types first and then programmatically excluding any child types with a status
of 0
. Is there a more efficient method for achieving this?