0

The scenario is as follows:

One product can be in Many orders, and one order can have many products. How to structure many-to-many relationships using mongoose and node.js ?

I have given the product model below. However, I am not sure how the order model should be. Can someone please help me figure this out. I am new to Node/ Mongoose and hope someone will help me out with this.

CODE

var mongoose = require('mongoose');

var productSchema = mongoose.Schema({
    product:{
        type: String,
        unique: true,
        required: true
    },
    price:{
        type: String,

        required: true

    },
    create_date:{
        type: Date,
        deault: Date.now
    }
});
Illep
  • 16,375
  • 46
  • 171
  • 302
  • Possible duplicate of [MongoDB Many-to-Many Association](http://stackoverflow.com/questions/2336700/mongodb-many-to-many-association) – chrisbajorin May 22 '16 at 18:45

1 Answers1

0

this is my product model

var mongoose = require('mongoose');
Schema = mongoose.Schema;
var productSchema = mongoose.Schema({
    product:{
        type: String,
        unique: true,
        required: true
    },
    price:{
        type: String,

        required: true

    },
    create_date:{
        type: Date,
        deault: Date.now
    }
});
var Product = mongoose.model('Product', productSchema);
module.exports = product;

this order model

var mongoose = require('mongoose');
    Schema = mongoose.Schema;
    var orderSchema = mongoose.Schema({
        orderNumber:{
            type: Number,
            required: true
        },
        products:[{type:Schema.Types.ObjectId, ref:'Product'}]
        create_date:{
            type: Date,
            deault: Date.now
        }
    });

    var Order = mongoose.model('Order', orderSchema);
module.exports = Order;

my result of json like this

product :

{
    _id:1
    product:"test",
    price:100,
    create_date:"20/11/91"

}

order :

{
    orderNumber:123
    product: [1] (ref of product id)
    create_date:"20/11/91"
}
karthi
  • 880
  • 6
  • 10
  • Can you show me how the `product`s model looks like. And also how to create the `order` (by showing me the JSON) – Illep May 24 '16 at 08:45
  • I am getting this error `"Cast to Array failed for value \"1\" at path \"product\""` – Illep May 25 '16 at 06:59