chr*_*hrs 8 javascript orm mongoose mongodb node.js
我正在构建一个个人商店应用程序,用户可以相互销售商品,但我很难搞清楚如何管理产品.例如,如果你想卖T恤,你应该能够选择尺寸和颜色等,但如果你卖电脑,你应该指定年份,CPU功率等.所有产品都有标题,价格,图像等在,但你会如何与不同的属性相处?我正在使用mongodb作为对象.
我在想一个字段attributes应该是一个具有不同细节的对象,然后是一个type可以定义存在哪些属性的字段.如果type = 'Computer那时我会知道attributes看起来像这样.
attributes: {
capacity: 1000 // gb
ram: 4096 // MB
}
Run Code Online (Sandbox Code Playgroud)
等等
在通常的面向对象设计中,我会通过继承/接口完成此操作.如果您对mongoose/node.js中的最佳方法有任何想法,我会很高兴听到它.
如果我在这个问题上没有说清楚,请告诉我什么是模糊的,应该澄清什么
编辑:
以下文章介绍了该问题的一种解决方案 http://learnmongodbthehardway.com/schema/chapter8/
但是它没有说明放置属性的位置.一种解决方案可能只是将其存储在类别本身中,但我不确定这里的最佳实践.
向Mongoose Schema添加继承的一种简单方法是使用Discriminators.这将允许您创建父架构,该架构可以存储所有产品中的属性,例如标题,价格和图像.然后,您可以创建子模式,其中包含特定于产品类型的属性,如电子和服装.例如,在电子模式中,您可以添加服装模式中不存在的cpu和ram的属性.
这是我如何使用Node和Mongoose进行设置的基本示例.
节点/ JavaScript的
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
// When you create a Electronic Product, it will set the type to Eletronic.
var options = { discriminatorKey: 'type' };
// parent Product schema.
var productSchema = new mongoose.Schema({ name: String, price: Number }, options);
var Product = mongoose.model('Product', productSchema);
// child Electronic schema.
var ElectronicProduct = Product.discriminator('Electronic', new mongoose.Schema({ cpu: Number }, options));
var computer = new ElectronicProduct({ name: 'computer', price: 100, cpu: 5 });
computer.save();
// child Clothing schema.
var ClothingProduct = Product.discriminator('Clothing', new mongoose.Schema({ size: String }, options));
var shirt = new ClothingProduct({ name: 'shirt', price: 50, size: 'Small' });
shirt.save();
Run Code Online (Sandbox Code Playgroud)
如果您记录保存的对象,它们应该是这样的
{ _id: 564b55983e5eec1ce2a44038,
type: 'Electronic',
cpu: 5,
price: 100,
name: 'computer' }
{ _id: 564b55983e5eec1ce2a44039,
type: 'Clothing',
size: 'Small',
price: 50,
name: 'shirt' }
Run Code Online (Sandbox Code Playgroud)
当您尝试访问不在Product模式中的属性时,最好在尝试访问该属性之前检查该属性是否存在.