Node.js 产品和捆绑包的MongoDB数据库设计
我正试图用mongoDB数据库构建一个基于Node.js的电子商务网站,但我遇到了一些数据库设计或我缺少的逻辑方面的问题 总之,我有Node.js 产品和捆绑包的MongoDB数据库设计,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我正试图用mongoDB数据库构建一个基于Node.js的电子商务网站,但我遇到了一些数据库设计或我缺少的逻辑方面的问题 总之,我有产品,包括价格、名称、说明等。。。和捆绑包,其中包含一系列产品(通过引用)。主要问题是当我必须订购时,我无法将产品和捆绑在一起 所以我已经有了一个产品模式: const productSchema = new mongoose.Schema({ file: { type: String, required: true, }, name:
产品
,包括价格、名称、说明等。。。和捆绑包
,其中包含一系列产品(通过引用)。主要问题是当我必须订购时,我无法将产品
和捆绑
在一起
所以我已经有了一个产品
模式:
const productSchema = new mongoose.Schema({
file: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
preparation: String,
allergics: {
type: Array,
required: true,
},
price: {
type: Number,
required: true,
},
// More fields
});
module.exports = mongoose.model('Product', productSchema);
以及一个捆绑包
架构,其中包含对产品的引用(捆绑包包含多个产品):
因此,当用户订购捆绑包或单个产品时,我使用以下模式:
const orderSchema = new mongoose.Schema({
orderedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
articlesId: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
},
],
itemsNumber: {
type: Array,
required: true,
},
amount: Number,
orderedAt: Date,
placeToShip: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Place',
},
});
module.exports = mongoose.model('Order', orderSchema);
正如您所看到的,我只参考了产品
,但我想参考产品
和捆绑
,我不知道这是否可行,或者这是否是这样设计数据库的错误方法
抱歉,如果这篇文章有点长,但我正在尽可能的清楚!非常感谢。如果您想在articleId
中引用产品
或捆绑
(取决于用户购买的捆绑或单个产品),您可以这样做:
不要在您的orderSchema
的articleId
字段中给出ref
,只需将其类型指定为ObjectId
const orderSchema = new mongoose.Schema({
...
articlesId: [
{
type: mongoose.Schema.Types.ObjectId
},
],
...
});
并且,在填充时告诉它要从哪个模型填充
//In case user bought a product
Order.find({findQuery})
.populate({path : '',model : 'Product'})
.exec(function(err,result){...});
//In case user bought a Bundle
Order.find({findQuery})
.populate({path : '',model : 'Bundle'})
.exec(function(err,result){...});
但是,您必须有一种方法来查明用户
购买了单个产品
或捆绑产品
。
希望对你有帮助 好的,非常感谢,今晚我会试试这个,让你了解最新情况!
//In case user bought a product
Order.find({findQuery})
.populate({path : '',model : 'Product'})
.exec(function(err,result){...});
//In case user bought a Bundle
Order.find({findQuery})
.populate({path : '',model : 'Bundle'})
.exec(function(err,result){...});