Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One to Many mapping in mongoose, How to receive and process?

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.

like image 855
Mike Avatar asked Jul 18 '13 01:07

Mike


People also ask

What is meant by one to many relationship in MongoDB?

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.

How do mongooses make relationships?

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.

What does findById return Mongoose?

Return value findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What is $Push in Mongoose?

$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.


1 Answers

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

like image 56
Peter Lyons Avatar answered Sep 28 '22 04:09

Peter Lyons