One to Many with Mongoose and ExpressJS - node.js

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?

Related

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 implement partial document embedding in Mongoose?

I have a simple relation between topics and categories when topic belongs to a category.
So schema looks like this:
const CategorySchema = new mongoose.Schema({
name: String,
slug: String,
description: String
});
And topic
const TopicSchema = new mongoose.Schema({
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
},
title: String,
slug: String,
body: String,
created: {type: Date, default: Date.now}
});
I want to implement particular embedding of category into topic
{
category: {
_id: ObjectId('abc'),
slug: 'catslug'
},
title: "Title",
slug: "topictitle",
...
}
It will help me avoid unnecessary population and obtain performance bonuses.
I don't want to embed whole document because I want to changes categories sometimes (it is a rare operation) and maintain references.
Hope this helps, done it in my own project to save some RTTs in common use cases. Make sure you're taking care of both copies on update.
parent.model.js:
const mongoose = require('mongoose');
const childEmbeddedSchema = new mongoose.Schema({
_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Child', auto: false, required: true, index: true},
someFieldIWantEmbedded: {type: String}
});
const parentSchema = new mongoose.Schema({
child: { type: childEmbeddedSchema },
moreChildren: { type: [{type: childEmbeddedSchema }] }
});
module.exports = mongoose.model('Parent', parentSchema);
child.model.js:
const mongoose = require('mongoose');
const childSchema = new mongoose.Schema({
someFieldIWantEmbedded: {type: String},
someFieldIDontWantEmbedded: {type: Number},
anotherFieldIDontWantEmbedded: {type: Date}
});
module.exports = mongoose.model('Child', childSchema);
parent.controller.js:
const mongoose = require('mongoose');
const Parent = require('path/to/parent.model');
exports.getAll = (req, res, next) => {
const query = Parent.find();
// only populate if requested! if true, will replace entire sub-document with fetched one.
if (req.headers.populate === 'true') {
query.populate({
path: 'child._id',
select: `someFieldIWantEmbedded ${req.headers.select}`
});
query.populate({
path: 'moreChildren._id',
select: `someFieldIWantEmbedded ${req.headers.select}`
});
}
query.exec((err, results) => {
if (err) {
next(err);
} else {
res.status(200).json(results);
}
});
};

How can I retrieve information from one collection into another collection in mongoose?

I have a student collection when I want to report on a particular student with
studentId the report must be stored in report collection along with studentId
and what report I gave.I want to use individual collections
here is student schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var studentSchema = new Schema({
name: {
type: String,
required: true
},
dateofbirth: {
type: Date,
required: true
},
schoolname:
{
type:String,
required:true
},
standard:
{
type: Number,
required:true
}
}, {
timestamps: true
});
and here is report schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var reportSchema = new Schema({
date: {
type:Date,
required:true
},
comment:
{
type:String,
required:true
}
},
{
timestamps: true
});
var Report = mongoose.model('report', reportSchema);
module.exports = Report;
So how can I retrive studenId from student collection ?And how can I give report to a particular student?
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var studentSchema = new Schema({
name: {type: String, required: true},
dateofbirth: {type: Date, required: true},
schoolname: {type:String, required:true},
standard: {type: Number, required:true},
timestamps: true
});
var reportSchema = new Schema({
date: {type:Date,required:true},
comment: {type:String,required:true}
timestamps: true,
student_id: [{type: String, ref:'student',required: true}] //store your student{_id} relation here ref ==> is just a Collection name
});
mongoose.connect('mongodb://localhost/your_db_name_here', {
// using mongoose client to avoid promises exception
useMongoClient: true,
});
//just making your collection available to next controller.js file
module.exports= {
student : mongoose.model('student',studentSchema ),
report: mongoose.model('report', reportSchema)
};
controller.js I have been using express.js for your case
var db = require("./db.js");
var app = require("express")();
app.post("/api/student/register", (req, res) => {
var dbdata = {
name: req.body.name,
.......
}
db.student.create(dbdata, (er, callback) => {
if(er)return res.json("error");
return res.json("successfully inserted");
});
});
app.post("/api/student/report/create", (req, res) => {
//while creating a report you have to pass a Student primary key
var dbdata = {
date: req.body.data;
comment: req.body.comment,
student_id: req.body.student_id
// similar to foreign key relation ship}
}
db.report.create(dbdata, function(er, callback){
if(er)return res.json("err");
return res.json("successfully inserted");
});
});
your answer here
app.post("/particular/student/report", function(req, res){
db.report.find({student_id:"your student id here"}).populate('student_id').exec(function(err, data){
if(err)return res.json("db exception");
return res.json(data); //you will get all your student report for the particular student
});
});
here is
mongoose populate official docs
still if you have some other basic thing about mongoose or mean stack means kinldy refer to https://github.com/Muthukumars1994/Meanapp

How to structure many-to-many relationships in mongoose nodejs?

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

Resources