2017-01-17 3 views
0

私はMongoDBのデータベースとのNode.jsに基づく電子商取引のウェブサイトを構築しようとしていると私はいくつかのデータベースの設計や、いくつかのロジックに関する問題が発生しています私は要約するとのMongoDBデータベース設計は

をしないのです価格、名前、説明などを含むProductと、製品の配列を含む(Bundle)があります。

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); 

そしてProductへのREFが含まれていBundleスキーマ:主な問題は、だから私はすでにProductスキーマを持って

...私が注文しなければならないとき、私は一緒にProductBundleを取得することはできません来ます(バンドルには、複数の製品が含まれています):

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); 

ユーザーはバンドルまたは単一の製品を注文するときだから、私はこのスキーマを使用します。

あなたが見ることができるように、私は唯一の Productに参照
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); 

、私はProductBundleに参照したい、これが可能であれば私は知らない、またはこれはそのようなデータベースを設計する間違った方法であれば。

申し訳ありませんが投稿は少し長いですが、私は可能な限り明確にしようとしています!どうもありがとう。

答えて

0

あなたはarticleIdに(利用者に応じて、バンドルまたは単一の製品を購入する)productまたはbundleを参照したい場合、あなたはこのようにそれを行うことができます。

いけないちょうどそのを指定し、あなたのorderSchemaarticleId分野でrefを与えますtypeObjectIdとする。

const orderSchema = new mongoose.Schema({ 
    ... 
    articlesId: [ 
    { 
     type: mongoose.Schema.Types.ObjectId 
    }, 
    ], 
    ... 
}); 

そして、 populateにどの modelから、それを伝える移入ながら。

//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){...}); 

しかし、あなたはuserは、単一のproductを買ったりbundle見つけるための方法を持っている必要があります。 あなたを助ける希望!

+0

ありがとう、私は今夜これを試してみましょう。 – antoine2vey

+0

この作品はありましたか?まだ試していますか? –