Dynamically create collection with Mongoose - node.js

I want to give users the ability to create collections in my Node app. I have really only seen example of hard coding in collections with mongoose. Anyone know if its possible to create collections dynamically with mongoose? If so an example would be very helpful.
Basically I want to be able to store data for different 'events' in different collections.
I.E.
Events:
event1,
event2,
...
eventN
Users can create there own custom event and store data in that collection. In the end each event might have hundreds/thousands of rows. I would like to give users the ability to perform CRUD operations on their events. Rather than store in one big collection I would like to store each events data in a different collection.
I don't really have an example of what I have tried as I have only created 'hard coded' collections with mongoose. I am not even sure I can create a new collection in mongoose that is dynamic based on a user request.
var mongoose = require('mongoose');
mongoose.connect('localhost', 'events');
var schema = mongoose.Schema({ name: 'string' });
var Event1 = mongoose.model('Event1', schema);
var event1= new Event1({ name: 'something' });
event1.save(function (err) {
if (err) // ...
console.log('meow');
});
Above works great if I hard code 'Event1' as a collection. Not sure I create a dynamic collection.
var mongoose = require('mongoose');
mongoose.connect('localhost', 'events');
...
var userDefinedEvent = //get this from a client side request
...
var schema = mongoose.Schema({ name: 'string' });
var userDefinedEvent = mongoose.model(userDefinedEvent, schema);
Can you do that?

I believe that this is a terrible idea to implement, but a question deserves an answer. You need to define a schema with a dynamic name that allows information of 'Any' type in it. A function to do this may be a little similar to this function:
var establishedModels = {};
function createModelForName(name) {
if (!(name in establishedModels)) {
var Any = new Schema({ any: Schema.Types.Mixed });
establishedModels[name] = mongoose.model(name, Any);
}
return establishedModels[name];
}
Now you can create models that allow information without any kind of restriction, including the name. I'm going to assume an object defined like this, {name: 'hello', content: {x: 1}}, which is provided by the 'user'. To save this, I can run the following code:
var stuff = {name: 'hello', content: {x: 1}}; // Define info.
var Model = createModelForName(name); // Create the model.
var model = Model(stuff.content); // Create a model instance.
model.save(function (err) { // Save
if (err) {
console.log(err);
}
});
Queries are very similar, fetch the model and then do a query:
var stuff = {name: 'hello', query: {x: {'$gt': 0}}}; // Define info.
var Model = createModelForName(name); // Create the model.
model.find(stuff.query, function (err, entries) {
// Do something with the matched entries.
});
You will have to implement code to protect your queries. You don't want the user to blow up your db.

From mongo docs here: data modeling
In certain situations, you might choose to store information in
several collections rather than in a single collection.
Consider a sample collection logs that stores log documents for
various environment and applications. The logs collection contains
documents of the following form:
{ log: "dev", ts: ..., info: ... } { log: "debug", ts: ..., info: ...}
If the total number of documents is low you may group documents into
collection by type. For logs, consider maintaining distinct log
collections, such as logs.dev and logs.debug. The logs.dev collection
would contain only the documents related to the dev environment.
Generally, having large number of collections has no significant
performance penalty and results in very good performance. Distinct
collections are very important for high-throughput batch processing.

Say I have 20 different events. Each event has 1 million entries... As such if this is all in one collection I will have to filter the collection by event for every CRUD op.
I would suggest you keep all events in the same collection, especially if event names depend on client code and are thus subject to change. Instead, index the name and user reference.
mongoose.Schema({
name: { type: String, index: true },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', index: true }
});
Furthermore I think you came at the problem a bit backwards (but I might be mistaken). Are you finding events within the context of a user, or finding users within the context of an event name? I have a feeling it's the former, and you should be partitioning on user reference, not the event name in the first place.
If you do not need to find all events for a user and just need to deal with user and event name together you could go with a compound index:
schema.index({ user: 1, name: 1 });
If you are dealing with millions of documents, make sure to turn off auto index:
schema.set('autoIndex', false);
This post has interesting stuff about naming collections and using a specific schema as well:
How to access a preexisting collection with Mongoose?

You could try the following:
var createDB = function(name) {
var connection = mongoose.createConnection(
'mongodb://localhost:27017/' + name);
connection.on('open', function() {
connection.db.collectionNames(function(error) {
if (error) {
return console.log("error", error)
}
});
});
connection.on('error', function(error) {
return console.log("error", error)
});
}
It is important that you get the collections names with connection.db.collectionNames, otherwise the Database won't be created.

This method works best for me , This example creates dynamic collection for each users , each collection will hold only corresponding users information (login details), first declare the function dynamicModel in separate file : example model.js
/* model.js */
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
function dynamicModel(suffix) {
var addressSchema = new Schema(
{
"name" : {type: String, default: '',trim: true},
  "login_time" : {type: Date},
"location" : {type: String, default: '',trim: true},
}
);
return mongoose.model('user_' + suffix, addressSchema);
}
module.exports = dynamicModel;
In controller File example user.js,first function to create dynamic collection and second function to save data to a particular collection
/* user.js */
var mongoose = require('mongoose'),
function CreateModel(user_name){//function to create collection , user_name argument contains collection name
var Model = require(path.resolve('./model.js'))(user_name);
}
function save_user_info(user_name,data){//function to save user info , data argument contains user info
var UserModel = mongoose.model(user_name) ;
var usermodel = UserModel(data);
usermodel.save(function (err) {
if (err) {
console.log(err);
} else {
console.log("\nSaved");
}
});
}

yes we can do that .I have tried it and its working.
REFERENCE CODE:
app.post("/",function(req,res){
var Cat=req.body.catg;
const link= req.body.link;
const rating=req.body.rating;
Cat=mongoose.model(Cat,schema);
const item=new Cat({
name:link,
age:rating
});
item.save();
res.render("\index");
});

I tried Magesh varan Reference Code ,
and this code works for me
router.post("/auto-create-collection", (req, res) => {
var reqData = req.body; // {"username":"123","password":"321","collectionName":"user_data"}
let userName = reqData.username;
let passWord = reqData.password;
let collectionName = reqData.collectionName;
// create schema
var mySchema = new mongoose.Schema({
userName: String,
passWord: String,
});
// create model
var myModel = mongoose.model(collectionName, mySchema);
const storeData = new myModel({
userName: userName,
passWord: passWord,
});
storeData.save();
res.json(storeData);
});

Create a dynamic.model.ts access from some where to achieve this feature.
import mongoose, { Schema } from "mongoose";
export default function dynamicModelName(collectionName: any) {
var dynamicSchema = new Schema({ any: Schema.Types.Mixed }, { strict: false });
return mongoose.model(collectionName, dynamicSchema);
}
Create dynamic model
import dynamicModelName from "../models/dynamic.model"
var stuff = { name: 'hello', content: { x: 1 } };
var Model = await dynamicModelName('test2')
let response = await new Model(stuff).save();
return res.send(response);
Get the value from the dynamic model
var Model = dynamicModelName('test2');
let response = await Model.find();
return res.send(response);

Related

Include non related collection in model result

I'm new to MongoDb and Mongoose and this might sound silly but I'm a bit confused about how things work.
I have two unrelated models: page model and team model that looks something like this:
// page.js
const mongoose = require('mongoose');
const schema = new mongoose.schema({
name: String,
body: {
title: String,
},
});
const Page = mongoose.model('Page', schema);
export default Page;
and
// team.js
const mongoose = require('mongoose');
const schema = new mongoose.schema({
name: String,
position: Number,
});
const Team = mongoose.model('Team', schema);
export default Team;
What I want to do is when I find one page (Page.findOne({...})) to include all teams. The result will look like this:
{
_id: 'some_id',
name: 'some name',
body: {
title: 'A title',
teams: [
{ name: 'Team1', position: 1 },
{ name: 'Team2', position: 2 },
// ...
{ name: 'Team3', position: 3 },
],
},
}
I looked at populate but this requires refs to other model.
Looked at virtuals but from what I understand this should work only with instance properties.
What will be the best approach to achieve this without adding relations between the two models?
This is I'm currently doing:
const pageResult = await Page.findOne({});
let page = pageResult.toObject();
page.body.team = await Team.find({});
well with out referencing, the only way to do that is to manually query Page model and findOne() what is the doc you want and then inside the callback of that findOne(), you will have to get Teams you desire with the value of Page.body.title value.
But its very easy to use Ref and populate using mongoose but if this is the way you really want to go knock yourself out mate ... :) cheers ...
Page.findOne({_id:req.body.id},(err,page)=>{
if(!err){
team.find({},(err,teams)=>{ // this will give you an array of teams
if(!err){
page.body.teams = teams; // this line set teams array from this callback to previous findOne()'s page obj
//so that you will finally create the object you want
}else{
throw err;
}
});
}else{
}
});
since you have only 2 fields in team model I think you won't be needing to use projections

Mongoose relations design

I've recently started using Mongoose with Express.js in a Node.js application and I have a question about a proper way to design my schemas.
I have several schemas that have some relationships, i.e. Location schema has an array of Objects (it's not a JS object in this context), and Object schema has its Location property. I've learned that relationships in Mongoose are resolved using population, but when I implemented this approach I noticed that I have to type a lot of duplicate code, i.e. whenever I want to create a new Object I have to also update the Location's array of Objects and then assign the Location to the Object's property. Wouldn't it be more trivial to just manually assemble all the Objects that has a locationId property equal to the Location that I want to get from the database in a separate query?
I have also considered just storing Objects in an array in a Location document (as subdocuments) but I decided that I want to be able to work with Objects (create, remove, update) separately from Locations (without querying a Location) so this approach doesn't fit my needs I guess. But then population has its drawbacks too in my case, so I guess it's really the best to just go with manually collecting Objects of a specific Location in a separate query by that Location's id.
I would like to hear an opinion of some professional or advanced user of this technology on designing Mongoose schemas so that I and others don't get into trouble later maintaining and scaling our applications.
Here are my current schemas in question:
var locationSchema = new mongoose.Schema({
title: String,
objects: [{ type: String, ref: 'object' }]
});
var objectSchema = new mongoose.Schema({
title: String,
location: { type: String, ref: 'location' }
});
Checkout this example
db/schemas.js:
const Schema = mongoose.Schema;
const ObjectSchema = {
title: Schema.Types.String
}
const LocationSchema = new Schema({
title: Schema.Types.String,
objects: [{type: Schema.Types.ObjectId, ref: 'Object'}]
})
module.exports = {
Object: ObjectSchema,
Location: LocationSchema
};
db/model.js:
const
mongoose = require('mongoose'),
schemas = require('./schemas');
module.exports = model => mongoose.model(model, schemas[model+'Schema']);
usage:
const
model = require('./db/model'),
LocationModel = model('Location');
LocationModel
.findOne({_id: 'some id here'})
.populate('objects')
.exec((err, LocationInstance) => {
console.log(LocationInstance.title, ' objects:', LocationInstance.objects);
});
when You create an object and want to relate to location:
const
model = require('./db/model'),
ObjectModel = model('Object'),
LocationModel = model('Location');
let
ObjectInstance = new ObjectModel({title: 'Something'});
ObjectInstance.save((err, result) => {
LocationModel
.findByIdAndUpdate(
'some id here',
{$push: {objects: ObjectInstance._id}},
(err) => {
console.log('Object:', ObjectInstance.title, ' added to location');
});
});
updating object data:
const
model = require('./db/model'),
ObjectModel = model('Object');
let id = 'id of object';
ObjectModel
.findByIdAndUpdate(
id,
{title: 'Something #2'},
(err) => {
console.log('Object title updated');
});
finding location by object:
const
model = require('./db/model'),
LocationModel = model('Object');
let id = 'id of object';
LocationModel
.findOne({objects: id})
.populate('objects')
.exec((err, LocationInstance) => {
console.log('Location objects:', LocationInstance.objects);
});
nothing special findOne({objects: id}) will search inside location documents that has relation by id in objects array
any other question welcome (:

How should I approach my back end design using the MEAN stack?

This is maybe more a case of looking for advice. However, I will supply sample code as an example of what I want to achieve. I am trying to build my first back end system and I keep running into problems with the design.
My MongoDB database consists of 4 major parts - Profiles, Teams, Drafts and Users. The profile (being the main data which sources everything using IDs) schema has properties to hold arrays with the Teams and Drafts IDs. The idea is that when the profile is served it will populate all those properties with the relevant data by using the IDs.
Example of the Profile schema using Mongoose:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserProfileSchema = new Schema({
Name : String,
Email : String,
Admin : Boolean,
Status : Number,
UserID : String,
PrivateProfile: Boolean,
Drafts: [String], //This array holds the draft IDs
Teams:[String] //Holds the team profiles IDs
});
module.exports = mongoose.model('UserProfile', UserProfileSchema);
Example of Team Profile Schema using Mongoose:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TeamProfileSchema = new Schema({
Name : String,
CaptainID : String,
CaptainName : String,
Members : [String], //Array of user IDs
DateCreated : Boolean,
Reputation : Number
});
module.exports = mongoose.model('TeamProfile', TeamProfileSchema);
Example of a route to find all the Team Profiles the user is the Captain of and fetch all the members associated with that team:
router.route('/teams/captain/:user_id')
.get(function (req, res) {
TeamProfile.find({
CaptainID : req.params.user_id
}, function (err, teams) {
if (err)
res.send(err);
for (var x in teams) {
var membersArray = [];
for (var i in teams[x].Members) {
var ID = teams[x].Members[i];
UserProfile.find({
UserID : ID
}, function (err, profile) {
if (err)
res.send(err);
membersArray.push(profile);
});
}
teams[x].Members = membersArray;
console.log(teams[x].Members);
}
res.json(teams);
});
})
I understand that the route will not work, but how do I pull this off? I used a more vanilla approach only for the purpose to explain what I want to achieve. Any help would be highly appreciated.
I advise you to use combination of denormalization and normalization.
because MongoDB is not a relational database.
denormalization is much faster then normalization. You don't need to use relationship anymore.
You can read this article hope may helpfull to you.
Cheers

How to populate the User object with Mongoose and Node

I am trying to add a couple of attributes to the scaffolded MEAN.js User entity.
locationName: {
type: String,
trim: true
}
I also have created another entity Book connected with User. Unfortunately, I think I do not quite grasp the concept behind the populate method because I am not able to "populate" the User entity with the locationName attribute.
I tried the following:
/**
* List of Books
*/
exports.list = function(req, res) {
Book.find().sort('-created').populate('user', 'displayName', 'locationName').exec(function(err, books) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(books);
}
});
};
Unfortunately, I get the following error:
/home/maurizio/Workspace/sbr-v1/node_modules/mongoose/lib/connection.js:625
throw new MongooseError.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "locationName".
Any suggestion?
Thanks
Cheers
The error is clear, you should have a schema for the locationName.
If your location is just a string property in your user model and does not refer to separate model, you don't need and shouldn't use populate with it, it will simply be returned as a property of the returned user object from mongoose find() method.
If your want to make your location a stand alone entity (different mongodb document), you should have a mongoose model that defines your location object, aka have a file in your app\models name for example: location.server.model.js that contains something like:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var LocationSchema = new Schema({
_id: String,
name: String
//, add any additional properties
});
mongoose.model('Location', LocationSchema);
Note that the _id here replaces the auto generated objectId, so this has to be unique, and this the property you should refer to in your User object, meaning if you have a location like this:
var mongoose = require('mongoose'),
Location = mongoose.model('Location');
var _location = new Location({_id:'de', name:'Deutschland'});
you should refer to it in your User object like this:
var _user=new User({location:'de'});
//or:
var _user=new User();
_user.location='de';
then you should be able to populate your location object with your user, like this:
User.find().populate('location').exec(function(err, _user) {
if (err) {
//handle error
} else {
//found user
console.log(_user);
//user is populated with location object, makes you able to do:
console.log(_user.location.name);
}
});
I suggest you to further read in mongodb data modeling and mongoose Schemas, Models, Population.

What are Mongoose (Nodejs) pluralization rules?

I am a newbie to the Node.js, Mongoose and Expressjs. I have tried to create a table "feedbackdata" using the Mongoose in MongoDB via the following code. But it is created as "feedbackdata*s*". By Googling, I found that the Mongoose uses pluralization rules. Anyone please help me to remove the pluralization rules? or how my code should be for the "feedbackdata" table?
Below is my code:
app.post("/save",function(req,res){
mongoose.connect('mongodb://localhost/profiledb');
mongoose.connection.on("open", function(){
console.log("mongo connected \n");
});
// defining schemar variables
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
// define schema for the feedbackdata table
var feedback_schema = new Schema({
_id: String,
url:String,
username:String,
email:String,
subscribe:String,
types:String,
created_date: { type: Date, default: Date.now },
comments: String
});
// accessing feeback model object
var feedback_table = mongoose.model('feedbackdata', feedback_schema);
var tableObj = new feedback_table();
var URL = req.param('url');
var name = req.param('name');
var email = req.param('email');
var subscribe = req.param('subscribe');
var choices = req.param('choices');
var html = req.param('html');
var receipt = req.param('receipt');
var feedbackcontent = req.param('feedbackcontent');
tableObj._id = 3;
tableObj.url = URL;
tableObj.username = name;
tableObj.email = email;
tableObj.subscribe = subscribe;
tableObj.types = choices;
tableObj.comments = feedbackcontent;
tableObj.save(function (err){
if(err) { throw err; }else{
console.log("Saved!");
}
mongoose.disconnect();
})
res.write("<div style='text-align:center;color:green;font-weight:bold;'>The above values saved successfully! <br><a href='/start'>Go back to feedback form</a></div>");
res.end();
});
The pluralization rules are in this file: https://github.com/LearnBoost/mongoose/blob/master/lib/utils.js
You can add your schema name to the 'uncountables' list, then mongoose will not pluralize your schema name.
Provide the name for the collection in options while creating schema object, then Mongoose will not do pluralize your schema name.
e.g.
var schemaObj = new mongoose.Schema(
{
fields:Schema.Type
}, { collection: 'collection_name'});
For more Info: http://mongoosejs.com/docs/guide.html#collection
The pluralization rules is here to ensure a specific naming convention.
The collection name should be plural, all lowercase and without spacing.
What are naming conventions for MongoDB?
I think you should ask yourself if you want to follow the main rule (ensured by mongoose as a default behavior) or get rid of it.
What are the perks ? What are the good points ?
You design first what is an user (User model) and then you store users into a collection. It totally make sense.
Your call.
If you ask yourself how to get the final name of the collection after the pluralization :
const newName = mongoose.pluralize()('User');

Resources