Reputation: 94
I am trying to build an e-commerce website based on Node.js with a mongoDB database and I am encountering problems about some database design or some logic I am missing
To sum up, I have Product
that contain price, name, description etc... and Bundle
that contains an array of products (by reference). The main problem come when I have to order, I can't get Product
AND Bundle
together ...
So I have already a Product
schema :
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);
And a Bundle
schema that contains ref to Product
(A bundle contains multiple products) :
const bundleSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
itemsId: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true,
}],
description: String,
reduction: {
type: Number,
min: 0,
default: 0,
max: 100,
},
});
module.exports = mongoose.model('Bundle', bundleSchema);
So when a user orders a bundle OR a single product, I use this schema :
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);
As you can see, I only reference to Product
, but I want to reference to Product
AND Bundle
, I don't know if this is possible, or if this is the wrong way to design the database like that.
Sorry if the post is a bit long, but I am trying to be as clear as possible! Thanks a lot.
Upvotes: 0
Views: 879
Reputation: 9268
if you want to reference product
or bundle
(depending on user buys bundle or single product) in articleId
, you can do it like this:
Dont give ref
in the articleId
field of your orderSchema
, just specify its type
as ObjectId
.
const orderSchema = new mongoose.Schema({
...
articlesId: [
{
type: mongoose.Schema.Types.ObjectId
},
],
...
});
And, while populating tell it which model
to populate
from.
//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){...});
But, you must have a way to find out user
bought a single product
or a bundle
.
Hope that helps you!
Upvotes: 1