I have 2 collections for product and product price. In product collection there is a field named product_id which is in String and the same field is in productprice collection with the same name as String.
How can I decide Schema for this and how to populate for which product comes with a field as productprice with it?
product fields : _id,Product_id,name
Product price fields :
_id,Product_id,price
where the same value is in Product_id for both the collections.
const productpriceSchema = mongoose.Schema({
Product_id: {
type: mongoose.Schema.ObjectID,
ref: 'Product'
},
price: String
});
const productSchema = mongoose.Schema({
Product_Name: type: String,
User_Object_ID :type: String,
cid :type: String
});
const Product = module.exports = mongoose.model('Product', productSchema);
const Productprice = module.exports = mongoose.model('Product_price', productpriceSchema);
module.exports.productwithprice = function(callback,limit){
Productprice.find({}, callback).populate('Product_id')
}
//Product Schema
//you don't have to give field _id, mongodb will automatically generate it.
const productSchema = new Schema({
Product_Id: String,
name: String
});
const Product = mongoose.model('Product', productSchema);
//Product Price Schema
const productPriceSchema = new Schema({
Product_Id: {
type: Schema.ObjectId,
ref: 'Product'
},
price: String
});
const ProductPrice = mongoose.model('ProductPrice', productPriceSchema)
ProductPrice.find({query})
.populate('Product_Id')
.exec((err, products) => {
//Logic
});
var ProductSchema = new Schema({
name: String,
productId: String
});
var PriceSchema = new Schema({
name: String,
productId: String
});
ProductSchema.virtual('price', {
ref: 'Price', // The model to use
localField: 'productId', // Find price where `localField`
foreignField: 'productId', // is equal to `foreignField`
// If `justOne` is true, 'price' will be a single doc as opposed to
// an array. `justOne` is false by default.
justOne: true
});
var Product = mongoose.model('Product ', ProductSchema);
var Price = mongoose.model('Price ', PriceSchema);
Product.find({}).populate('price').exec(function(error, products) {
/* `products.price` is available now */
});
For detail, please check Populate Virtuals section of Mongoose population.
Related
I have two schemas, one collection and another category. A collection has many category and a category can have many collection items.
I'm looking to create a filter later on down the line.
category schema
const mongoose = require('mongoose')
let categorySchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
collections: [{ type: mongoose.Types.ObjectId, ref: 'Collection' }]
})
module.exports = mongoose.model('category', categorySchema)
collection schema
const mongoose = require('mongoose')
let collectionSchema = new mongoose.Schema({
...
categories: [{
type: mongoose.Schema.Types.ObjectId, ref: 'categories',
required: true
}]
})
module.exports = mongoose.model('collection', collectionSchema)
truncated this to keep it relevant.
I'm not looking to populate the references yet as I'm only doing the backend for now, so I'm only rendering JSON for now.
I can create multiple category
and I can create a collection with a category as a collection must have at least one category
I can edit a collection and add a new category
However, sometimes I seem to get the following error
I'm not sure why maybe the database hasn't updated in the app, I am using nodemon so I'm not really sure what the issue could be here.
const CollectionSchema = new Schema({
name: String
categoryName: String
});
const CategorySchema = new Schema({
name: String
});
CollectionSchema.virtual('category', {
ref: 'Category', // The model to use
localField: 'name', // Find people where `localField`
foreignField: 'categoryName', // is equal to `foreignField`
// If `justOne` is true, 'members' will be a single doc as opposed to
// an array. `justOne` is false by default.
justOne: false,
options: { sort: { name: -1 }, limit: 5 } //you can add options as well
});
const Category = mongoose.model('Category', CategorySchema);
const Collection = mongoose.model('Collection', CollectionSchema);
Collection.find({}).populate('category').exec(function(error, categories) {
/* `categories.members` is now an array of instances of `Category` */
});
This link has additional Information
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
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
I succeed to make a deep population with find and the search key in first model, but now i want to find by key on the sub object generated by the deep populate.
I have three models : Product, Category, and Event
I want to find my Products by e_fk_club_id that is in Event model
I tried two solutions but they didn't work
First solution in find :
model.find({'categories.events.e_fk_club_id':id})`
Second solution with match :
`$match : { e_fk_club_id : id }`
these are my models
product.js
var ProductSchema = new mongoose.Schema({
p_id: Number,
p_name: String,
p_fk_category: {type: mongoose.Schema.Types.ObjectId, ref: 'categories'},
}
, {collection: 'products'});
module.exports = mongoose.model('products', ProductSchema);
Category.js
var CategorySchema = new mongoose.Schema({
c_id: Number,
c_name: String,
c_fk_event: {type: mongoose.Schema.Types.ObjectId, ref: 'events'},
}
, {collection: 'categories'});
module.exports = mongoose.model('categories', CategorySchema);
Event.js
var EventSchema = new mongoose.Schema({
e_id: Number,
e_name: String,
e_fk_club_id: Number,
}
, {collection: 'events'});
module.exports = mongoose.model('events', EventSchema);
This is the code which i am trying to fetch the data :
getProductsByClub:function (id, callback){
var model = require("Product");
//model
model .find({'categories.events.e_fk_club_id':id})
.populate({
path:'p_fk_category',
model:'categories',
populate:
{
path:'e_fk_event',
model:'events',
//$match : { e_fk_club_id : id }
}
})
.exec (function(err, doc){
if (err) {
callback(err) ;
} else {
callback(doc) ;
}
})
},
Is There any solution.
Thank you in advance.
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?