How to define a single reference schema using mongoose - node.js

I am new in node.js and mongodb and as in the below code i define a reference in table employee of department but here when I insert or get data from employee table i always get in array format but i want to define reference as single column not multiple.
var employee = new mongoose.Schema({
name: String,
dept: [department]
});
var department = new mongoose.Schema({
dept_name : String,
dept_code : String
})
I want data in response from employee table in format `{"name":"CS",dept:{"id":_id_of_dept}}
Please guide me the correct way to achieve my objective.

You can only nest using references or arrays, so in this example, you can either create a department record and reference that in the employee document, or have an array of departments for the employee (which I understand is not what you want to do).
To reference the department document from your employee you would use something like:
var department = new mongoose.Schema({
dept_name : String,
dept_code : String
});
mongoose.model('Department', department);
var employee = new mongoose.Schema({
name: String,
dept: { type: Schema.Types.ObjectId, ref: 'Department' }
});
However, then you'll need to populate when querying your employee to gather the department data.
But at a high level, looking at what you're trying to accomplish, I'd suggest just directly storing the department within the employee document. Relational databases may often end up with patterns like you've described above, but in document based databases, there's really not a good reason to separate out the department from the employee. Doing something like what I've put below will help you in the future for queries and general access of the data:
var employee = new mongoose.Schema({
name: String,
dept: {
dept_name : String,
dept_code : String
}
});
This answer might be helpful in understanding what I mean.

Related

Mongodb Collection name

I've created a database in MongoDB using mongoose. Although everything works fine, but when I check mongodb the name of the collection has extra 's' in its name. The collection name created is employees. What could be wrong, or is it just the naming convention of mongoose?
const mongoose = require('mongoose');
let employeeSchema = mongoose.Schema({
name: String,
email: String,
department: String,
doj: Date,
address: String
});
const Employee = mongoose.model("employee", employeeSchema);
module.exports = Employee;
It doesn't just add an extra 's' but it makes the correct plural of the name.
For Example : Mouse will be converted to mice
You can disable it by:
mongoose.pluralize(null);
Reference Link: https://github.com/Automattic/mongoose/issues/5947
So you have two options for controlling document names in mongoose.
If you just want to disable pluralization, you can do it with mongoose.pluralize(null) as in Ankit's answer.
And if you want to change your collection name whatever you want, you can do:
mongoose.model("employee", employeeSchema, { collection: 'myEmployee' } )

Am I better off splitting an elaborate mongoose model?

Assuming the case of a /login API, where, for a matching set of credentials, a user object from the collection should be returned, which approach would be more performant:
1) One model with projection queries:
var UserSchema = new Schema({
name : String,
email : String,
dob : Number,
phone : Number,
gender : String,
location : Object, // GeoJSON format {type: 'Point', geometry: { lat: '23.00', lng: '102.23' }}
followers : [UserSchema],
following : [UserSchema],
posts : [PostSchema],
groups : [GroupSchema]
// ... and so on
});
2) Split models:
var UserMinimalSchema = new Schema({
name : String,
email : String,
phone : Number,
location : Object,
});
var UserDetailSchema = new Schema({
dob : Number,
gender : String,
followers : [UserSchema],
following : [UserSchema],
posts : [PostSchema],
groups : [GroupSchema]
// ... and so on
});
Let's say:
For a logged-in user, only id, name, email, phone and location are to be returned.
The first model will use a projection query to return the properties in (1).
In the second case, only the UserMinimalSchema would be used to query the entire document.
Essentially both queries return exactly the same amount of data as mentioned in (1).
Assume that average user object is ~16MB limit and there are 1 Million records.
If someone performed such a test/links to documentation, it would be of great help to see how much it will matter to split or not.
I would not use split models:
You'll have to perform a population query everytime you want to look all of the user's data
You're increasing your data storage (you now will have to reference the user in your user details schema.
When Mongo will go do a lookup, it will find references to model instances and only extract data that you've specified in your projection query anyways. It will not load the entire object into memory unless you specify that in your query.

Reporting in mongodb

I have report generating in my first node application. I used mongodb and express. I have three collections: salary rule, Leave and Employee. I want to generate employees salary by using these collections.
I found phantomjs to export pdf. I used ejs template to generate html.
I got json values from the following scenario.
find Salary rule
find All Employees
find all Leaves by date range.
Match employees and leaves by employee id and calculate the salary.
put the result json into the array and generate html by ejs
export html to pdf by using phantomjs.
I am confused that this scenario could be hit performance and error-prone. I cannot find any suitable examples for exporting in node and mongodb.
My question is-
Is it bad idea to use mongodb in this scenario or is it normal flow?
Or do I need to change my mongodb collection schema?
Leave
var schema = new mongoose.Schema({
date: { type: Date, default: Date.now },
description: String,
type: String, // paid or unpaid
empName : String,
empId : String
});
Employee
var schema = new mongoose.Schema({
id: String,
name: String,
basicSalary: Number,
active: Boolean
});
Salary Rule
var schema = new mongoose.Schema({
totalHoliday: Number,
overtimeFee: Number,
unpaidLeaveFee: Number
});
IMO looks like exporting your data to a Relational Database could be easy to generate the report.
BUT if you still want to do this with MongoDB you could do a mapReduce.
https://docs.mongodb.com/manual/reference/method/db.collection.mapReduce/
your last two steps are the same but change the way that you get the data.

Best way to structure my mongoose schema: embedded array , populate, subdocument?

Here is my current Schema
Brand:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BrandSchema = new mongoose.Schema({
name: { type: String, lowercase: true , unique: true, required: true },
photo: { type: String , trim: true},
email: { type: String , lowercase: true},
year: { type: Number},
timestamp: { type : Date, default: Date.now },
description: { type: String},
location: { },
social: {
website: {type: String},
facebook: {type: String },
twitter: {type: String },
instagram: {type: String }
}
});
Style:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var StyleSchema = new mongoose.Schema({
name: { type: String, lowercase: true , required: true},
});
Product
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new mongoose.Schema({
name: { type: String, lowercase: true , required: true},
brandId : {type: mongoose.Schema.ObjectId, ref: 'Brand'},
styleId: {type: mongoose.Schema.ObjectId, ref: 'Style'},
year: { type: Number },
avgRating: {type: Number}
});
Post:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PostSchema = new mongoose.Schema({
rating: { type: Number},
upVote: {type: Number},
brandId : {type: mongoose.Schema.ObjectId, ref: 'Brand'},
comment: {type: String},
productId: {type: mongoose.Schema.ObjectId, ref: 'Style'},
styleId: {type: mongoose.Schema.ObjectId, ref: 'Style'},
photo: {type: String}
});
I'm currently making use of the mongoose populate feature:
exports.productsByBrand = function(req, res){
Product.find({product: req.params.id}).populate('style').exec(function(err, products){
res.send({products:products});
});
};
This works, however, being a noob --- i've started reading about performance issues with the mongoose populate, since it's really just adding an additional query.
For my post , especially, it seems that could be taxing. The intent for the post is to be a live twitter / instagram-like feed. It seems that could be a lot of queries, which could greatly slow my app down.
also, I want to be able to search prodcuts / post / brand by fields at some point.
Should i consider nesting / embedding this data (products nested / embedded in brands)?
What's the most efficient schema design or would my setup be alright -- given what i've specified I want to use it for?
User story:
There will be an Admin User.
The admin will be able to add the Brand with the specific fields in the Brand Schema.
Brands will have associated Products, each Product will have a Style / category.
Search:
Users will be able to search Brands by name and location (i'm looking into doing this with angular filtering / tags).
Users will be able to search Products by fields (name, style, etc).
Users will be able to search Post by Brand Product and Style.
Post:
Users will be able to Post into a feed. When making a Post, they will choose a Brand and a Product to associate the Post with. The Post will display the Brand name, Product name, and Style -- along with newly entered Post fields (photo, comment, and rating).
Other users can click on the Brand name to link to the Brand show page. They can click on the Product name to link to a Product show page.
Product show page:
Will show Product fields from the above Schema -- including associated Style name from Style schema. It will also display Post pertaining to the specific Product.
Brand show page:
Will simply show Brand fields and associated products.
My main worry is the Post, which will have to populate / query for the Brand , Product, and Style within a feed.
Again, I'm contemplating if I should embed the Products within the Brand -- then would I be able to associate the Brand Product and Style with the Post for later queries? Or, possibly $lookup or other aggregate features.
Mongodb itself does not support joins. So, mongoose populate is an attempt at external reference resolution. The thing with mongodb is that you need to design your data so that:
most of you queries need not to refer multiple collections.
after getting data from query, you need not to transform it too much.
Consider the entities involved, and their relations:
Brand is brand. Doesn't depend on anything else.
Every Product belongs to a Brand.
Every Product is associated with a Style.
Every Post is associated with a Product.
Indirectly, every Post is associated to a Brand and Style, via product.
Now about the use cases:
Refer: If you are looking up one entity by id, then fetching 1-2 related entities is not really a big overhead.
List: It is when you have to return a large set of objects and each object needs an additional query to get associated objects. This is a performance issue. This is usually reduced by processing "pages" of result set at a time, say 20 records per request. Lets suppose you query 20 products (using skip and limit). For 20 products you extract two id arrays, one of referred styles, and other of referred brands. You do 2 additional queries using $in:[ids], get brands and styles object and place them in result set. That's 3 queries per page. Users can request next page as they scroll down, and so on.
Search: You want to search for products, but also want to specify brand name and style name. Sadly, product model only holds ids for style and brand. Same issue with searching Posts with brand and product. Popular solution is to maintain a separate "search index", a sort of table, that stores data exactly the way it will be searched for, with all searchable fields (like brand name, style name) at one place. Maintaining such search collections in mongodb manually can be a pain. This is where ElasticSearch comes in. Since you are already using mongoose, you can simply add mongoosastic to your models. ElasticSearch's search capabilities are far greater than a DB Storage engine will offer you.
Extra Speed: There is still some room for speeding things up: Caching. Attach mongoose-redis-cache and have frequent repeated queries served, in-memory from Redis, reducing load on mongodb.
Twitter like Feeds: Now if all Posts are public then listing them up for users in chronological order is a trivial query. However things change when you introduce "social networking" features. Then you need to list "activity feeds" of friends and followers. There's some wisdom about social inboxes and Fan-out lists in mongodb blog.
Moral of the story is that not all use cases have only "db schema query" solutions. Scalability is one of such cases. That's why other tools exist.

Mongoose Populate Returning null due to Schema design?

I'm stuck with mongoose populate returning null. I have a very similar situation to another question where it seems to we working just fine, perhaps with one important difference:
The model I'm referencing only exist as a subdocument to another model.
Example:
// The model i want to populate
Currency = new Schema({
code: String,
rate: Number
});
// The set of currencies are defined for each Tenant
// A currency belongs to one tenant, one tenant can have multiple currencies
Tenant = new Schema({
name: String,
currencies: [Currency]
});
Product = new Schema({
Name: String,
_currency: {type: ObjectId, ref: 'Currency'},
});
Customer = new Schema({
tenant: {type: ObjectId, ref: 'Tenant'},
products: [ Product ]
});
Then I export the models and use them in one of my routes where what I would like to do is something like
CustomerModel.find({}).populate('products._currency').exec(function(err, docs){
// docs[0].products[0]._currency is null (but has ObjectId if not usinn populate)
})
Which is returning null for any given product._currency but if I don't populate i get the correct ObjectId ref, which corresponds to an objectId of a currency embedded in a tenant.
I'm suspecting I need currencies to be stand-alone schema for this to work., Ie not just embedded in tenant, but that would mean I get a lot of schemas referencing each other.
Do you know if this is the case, or should my set-up work?
If this is the case, I guess I just have to bite the bullet and have multitude of collections referencing each other?
Any help or guidance appreciated!

Resources