I know there have been a lot of discussion about ref and embed schema in mongoose schema. I am kinda learning node and I have a background of RDBMs . I am working with mongoose. I have a scenario which is quite simple and i have implement it pretty much. The point where I am stuck is either to use embed or ref.
Scenario
My scenario is , I have two models product & categories. The relation b/w them is many to many. First let me show you my models.
Category schema
const mongoose = require('mongoose');
//function to call monggose schema
const CategorySchema = mongoose.Schema({
category_name: {
type: String,
required: true
}
})
const Category = module.exports = mongoose.model('Category', CategorySchema);
Product schema
const mongoose = require('mongoose');
const ProductSchema = mongoose.Schema({
product_name: {
type: String,
required: true
},
product_rating: {
type: Number,
required: true
},
product_price: {
type: String,
required: true
},
product_btc: {
type: String,
required: true
},
product_mode: {
type: String,
required: true
},
product_date: {
type: String,
required: true
},
product_hasrate: {
type: String,
required: true
},
product_powerConsumption: {
type: String,
required: true
},
product_efficiency: {
type: String,
required: true
},
product_voltage: {
type: String,
required: true
},
product_frequency: {
type: String,
required: true
},
product_shipment: {
type: String,
required: true
},
product_warranty: {
type: String,
required: true
},
product_contact: {
type: String,
required: true
},
category: [mongoose.Schema.Types.Mixed]
})
const Product = module.exports = mongoose.model('Product', ProductSchema);
As I am making the front-end too in angularjs I am confused also. I have three documents in my category table which i filled using postman. I am looking at things from front-end angle. I shall have a dropdown of categories and user shall select or multi select the categories for its product.
Now how would I store the categories in Product schema. They are storing right now, But i dont thing I am doing it right. I want to use referencing but may be I am mixing both embed and ref .
I want to get all the product across a single category in my search API and I want to get all the categories of my products too.
I am reading mongoose docs too, but i am getting confused more. Because the example they gave is not relevant to what i describe above.
var author = new Person({
_id: new mongoose.Types.ObjectId(),
name: 'Ian Fleming',
age: 50
});
author.save(function (err) {
if (err) return handleError(err);
var story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
If i am not wrong they care creating the person and the story at the same time. While I have already made categories. kindly shed some light over this problem.