The problem I have is a One to many mapping with mongoose(Mongodb). The one is the Order(buyer data) and the many is the Items(price,quantity,etc).
1) How I should create the Schema for the the Order and items, like should I put the items in an array in the order?
2) Would all the data be in one post function?
I herd you can use ObjectId to link the many to one but I am not sure how to.
One-To-Many (1:N) The 1:N relationship describes a relationship where one side can have more than one relationship while the reverse relationship can only be single sided. An example is a Blog where a blog might have many Comments but a Comment is only related to a single Blog.
To model relationships between connected data, you can reference a document or embed it in another document as a sub document. Referencing a document does not create a “real” relationship between these two documents as does with a relational database. Referencing documents is also known as normalization.
Return value findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .
$push. The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
Since an Order sounds like it will have a relative small number of items, the simplest thing would probably be just a list of item Ids:
var OrderSchema = new mongoose.Schema({
items: [{type: mongoose.Schema.Types.ObjectId, ref: 'Item'}]
});
var ItemSchema = new mongoose.Schema({
price: Number,
quantity: Number
});
Most UIs would not build an entire order in a single POST function, so it's probably best to allow creating an order and then separately adding items to it via order.items.push(itemId).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With