How to structure many-to-many relationships in mongoose nodejs? - node.js

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

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"
}

Related

How to create a dynamic nested mongoose document with the same schema on multiple levels

Before everyone tells me I can't call a const before initializing, I do know that.
But I think this is the simplest way to render the concept I have in mind, (where any subdocument within the replies array also has the same schema as the parent, and documents within the replies array of those subdocuments also having the same schema). I would really appreciate anyone's input.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
replies: [commentSchema]
});
module.exports = mongoose.model("comment", commentSchema);
Since a const can't be called before initialization, to fix this issue the parent schema should be called on the children array after initialization the code below:
commentSchema.add({ replies: [commentSchema] })
The final result should look like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
});
commentSchema.add({ replies: [commentSchema] })

how to populate nested array using mongoose

assuming i have this 2 schemas
company schema with an array of categories
//category
export const CategorySchema = new mongoose.Schema({
name: { type: String },
}, { timestamps: true });
//company
export const CompanySchema = new mongoose.Schema({
user: { type: Schema.Types.ObjectId, ref: 'User' },
name:String,
email:String,
categories:{type: [CategorySchema], default: [] },
}, { timestamps: true });
product schema with category as a ref to the category from company
export const ProductSchema =new mongoose.Schema({
name:String,
category:{ type: Schema.Types.ObjectId, ref: 'Category' },
}, { timestamps: true })
is it possible to populate category from the product ?
i tried this code and it's not working
const products=await this.productModel.find({}).populate({'path':"category","model":"Category"}) ``
what you need is just
productModel.find({}).populate("category")
try this code for populate
const products=await this.productModel.find({}).populate({'path':"category","model":"company.categories"})

How can i display products per each category stored in MongoDB

currently i created a schema for storing products using mongoose as below
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
title: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
quantity: {
type: Number,
required: true
},
manufacture: {
type: String,
required: true
},
creator: {
type: Schema.Types.ObjectId,
ref: 'user'
},
category: {
type: Schema.Types.ObjectId,
ref: 'category'
}
});
module.exports = { Product: mongoose.model('product', ProductSchema) };
and here another schema for storing categories that products are related to
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
title: {
type: String,
required: true
}
});
module.exports = { Category: mongoose.model('category', CategorySchema) };
each product is related to a category
the question is how can i display all products that are related to a specific category.
i tried .find() method but i can't use it correctly.
thanks for any advice
You need to use .populate('category'), after .find() in order to populate all the connected data.
products.find().populate('category').exec((err, product) => { })

How to connect schemas with each other in mongooseJS?

Basically what I am trying to achieve is the following:
In my iOS application a QR-Code can be scanned to get the ID of a specific lounge and with that its JSON data (only ID and name for now) saved in MongoDB.
Every lounge is able (but doesn't have to) to add products to their lounge, so that in the end, after scanning the QR-Code, a customer is able to see which products are offered.
A product contains only a name and imageURL for now, but not a price, because the price can variate and be set by owners of a lounge. So a price of one and the same product can be different.
I would like to know, what the correct and best way is for implementing the schemas for that approach, so that I can easily fetch all products of a specific lounge, maybe based on its ID.
What I got so far:
lounge.js:
const mongoose = require('mongoose');
const loungeSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true }
});
module.exports = mongoose.model('Lounge', loungeSchema);
product.js
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
imageURL: { type: String, required: true, unique: true }
});
module.exports = mongoose.model('Product', productSchema);
Basically you can use mongoose populate. You can achieve this by storing the products in separate collection and basically populate an array on the lounge schema using the _id for the lounge let me show you an example:
Your lounge schema would be something like this
const mongoose = require('mongoose');
const loungeSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true }
products: [type: Schema.Types.ObjectId, ref: 'Products' ]
});
module.exports = mongoose.model('Lounge', loungeSchema);
And your product schema
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
imageURL: { type: String, required: true, unique: true }
});
module.exports = mongoose.model('Product', productSchema);
When saving creating a lounge just add the _id of the product to products array that apart of the lounge schema.
So basically you find the product and retrieve its _id.
To run a find query it would be something like this:
lounge.find({}).populate('products').exec();
products array will then have the related products for each lounge

One to Many with Mongoose and ExpressJS

I'm trying to create a one-to-many relationship with Category and Product.
I only have the _category_id on product model.
How I can see all products for a specific category?
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: {
type: String,
default: '',
trim: true
},
_category: {
type: Schema.Types.ObjectId,
ref: 'Category'
}
});
mongoose.model('Product', ProductSchema);
var CategorySchema = new Schema({
name: {
type: String,
default: '',
trim: true
}
});
CategorySchema.statics = {
load: function(id, cb) {
this.findOne({ _id: id }).exec(cb);
}
};
mongoose.model('Category', CategorySchema);
I think I need to add the products variable or something like that on load method.
How I can do that?

Resources