简体   繁体   中英

E commerce Schema design for MongoDB and Mongoose

I am trying to design my schema for an ecommerce web store that sells shirts. I am using a framework that will generate the HTML views based on information retrieved from the database (so that, if there are eight shirt colors, eight different pictures will be shown, if one of those colors is out of stock, it will not be show, etc)

So, my question is this:

The web store primarily revolves around the shirts. There is one edition of shirts (right now), and eight colors. I was planning to make just one Mongoose Schema , a "Shirt" schema, and include all the information in the shirt schema. However, it seems that if I want to get the total number of colors (so that I can display one shirt in each color), I would have to loop through all of the shirts in the shirts collection, and tally the colors.

This would involved looping through thousands of shirts to figure out if all 8 colors are in stock.

Is there an easier and faster way to do this?

Yup. There's a distinct command that can do this efficiently if you have an index on shirt color:

> db.test.drop()
> db.test.ensureIndex({ "color" : 1 })
> for (var i = 0; i < 10000; i++) db.test.insert({ "color" : i % 13 })
> db.test.distinct("color")
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

Bypass the helper and run the command directly to see information about how the distinct was run:

> db.runCommand ( { distinct: "test", key: "color" } )
{
    "values" : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ],
    "stats" : {
        "n" : 13,
        "nscanned" : 13,
        "nscannedObjects" : 0,
        "timems" : 0,
        "cursor" : "DistinctCursor"
    },
    "ok" : 1
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM